Linq使用Select淺談
在向大家詳細(xì)介紹Linq使用Select之前,首先讓大家了解下Linq To Sql查詢(xún)數(shù)據(jù)庫(kù),然后全面介紹Linq使用Select。
下面通過(guò)一些例子來(lái)說(shuō)明怎樣Linq使用Select,參考自:LINQ Samples
1. 可以對(duì)查詢(xún)出來(lái)的結(jié)果做一些轉(zhuǎn)換,下面的例子在數(shù)組中查找以"B"開(kāi)頭的名字,然后全部轉(zhuǎn)成小寫(xiě)輸出:
- string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" };
- var rs = from n in names
- where n.StartsWith("B")
- select n.ToLower();
- foreach (var r in rs)
- Console.WriteLine(r);
2. 返回匿名類(lèi)型,比如Linq To Sql查詢(xún)數(shù)據(jù)庫(kù)的時(shí)候只返回需要的信息,下面的例子是在Northwind數(shù)據(jù)庫(kù)中查詢(xún)Customer表,返回所有名字以"B"開(kāi)頭的客戶的ID和名稱(chēng):
- NorthwindDataContext dc = new NorthwindDataContext();
- var cs = from c in dc.Customers
- where c.ContactName.StartsWith("B")
- select new
- {
- CustomerID = c.CustomerID,
- CustomerName = c.ContactTitle + " " + c.ContactName
- };
- foreach (var c in cs)
- Console.WriteLine(c);
3. 對(duì)于數(shù)組,select可以對(duì)數(shù)組元素以及索引進(jìn)行操作:
- 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. 組合查詢(xún),可以對(duì)多個(gè)數(shù)據(jù)源進(jìn)行組合條件查詢(xún)(相當(dāng)于Linq使用SelectMany函數(shù)),下面的例子其實(shí)就相對(duì)于一個(gè)雙重循環(huán)遍歷:
- int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
- int[] numbersB = { 1, 3, 5, 7, 8 };
- var pairs =
- from a in numbersA,
- b in numbersB
- where a < b
- select 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的話,相當(dāng)于進(jìn)行一次子查詢(xún):
- NorthwindDataContext dc = new NorthwindDataContext();
- var rs = from c in dc.Customers
- from o in c.Orders
- where o.ShipCity.StartsWith("B")
- select new { CustomerName = c.ContactName, OrderID = o.OrderID };
- foreach (var r in rs)
- Console.WriteLine(r);
【編輯推薦】