LINQ 中的 select

來源:互聯網
上載者:User

下面通過一些例子來說明怎樣使用select,參考自:LINQ Samples

1.  可以對查詢出來的結果做一些轉換,下面的例子在數組中尋找以"B"開頭的名字,然後全部轉成小寫輸出:

 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. 返回匿名型別,比如Linq To Sql查詢資料庫的時候只返回需要的資訊,下面的例子是在Northwind資料庫中查詢Customer表,返回所有名字以"B"開頭的客戶的ID和名稱:

 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. 對於數組,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 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的話,相當於進行一次子查詢:

  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); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.