LINQ 中的 select
生活随笔
收集整理的這篇文章主要介紹了
LINQ 中的 select
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面通過一些例子來說明怎樣使用select,參考自:LINQ Samples
1.? 可以對查詢出來的結果做一些轉換,下面的例子在數組中查找以"B"開頭的名字,然后全部轉成小寫輸出:
string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" };var rs = from n in nameswhere n.StartsWith("B")select n.ToLower();foreach (var r in rs)Console.WriteLine(r);2. 返回匿名類型,比如Linq To Sql查詢數據庫的時候只返回需要的信息,下面的例子是在Northwind數據庫中查詢Customer表,返回所有名字以"B"開頭的客戶的ID和名稱:
NorthwindDataContext dc = new NorthwindDataContext();var cs = from c in dc.Customerswhere c.ContactName.StartsWith("B")select new{CustomerID = c.CustomerID,CustomerName = c.ContactTitle + " " + c.ContactName};foreach (var c in cs)Console.WriteLine(c);3. 對于數組,select可以對數組元素以及索引進行操作:
string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" };var rs = names.Select((name, index) => new { Name = name, Index = index });foreach (var r in rs)Console.WriteLine(r);4. 組合查詢,可以對多個數據源進行組合條件查詢(相當于使用SelectMany函數),下面的例子其實就相對于一個雙重循環遍歷:
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };int[] numbersB = { 1, 3, 5, 7, 8 };var pairs =from a in numbersA,b in numbersBwhere a < bselect new {a, b};Console.WriteLine("Pairs where a < b:");foreach (var pair in pairs)Console.WriteLine("{0} is less than {1}", pair.a, pair.b);??而用Linq To Sql的話,相當于進行一次子查詢:
NorthwindDataContext dc = new NorthwindDataContext();var rs = from c in dc.Customersfrom o in c.Orderswhere o.ShipCity.StartsWith("B")select new { CustomerName = c.ContactName, OrderID = o.OrderID };foreach (var r in rs)Console.WriteLine(r);
?
總結
以上是生活随笔為你收集整理的LINQ 中的 select的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 签到送集分宝的地方
- 下一篇: 什么是注入式攻击(2)