C# Linq

來源:互聯網
上載者:User

標籤:

linq可以對多種資料來源和對象進行查詢,可以減少代碼量,提高檢索效率。

感覺linq很像sql。。,但是語句的順序不同

linq的查詢形式如下:

  from...

  select...

  where...

例如查詢偶數:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace linq{    class Program    {        static void Main(string[] args)        {            // The Three Parts of a LINQ Query:            //  1. Data source.            int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };            // 2. Query creation.            // numQuery is an IEnumerable<int>            var numQuery =                from num in numbers                where (num % 2) == 0                select num;            // 3. Query execution.            foreach (int num in numQuery)            {                Console.Write("{0} ", num);            }        }    }}

結果:0 2 4 6 請按任意鍵繼續. . .

where語句可以使用&&和||:

var numQuery =                from num in numbers                where (num % 2) == 0&&(num%4)!=0                select num;

結果為:

2 6 請按任意鍵繼續. . .

var numQuery =                from num in numbers                where (num % 2) == 0||(num%3)==0                select num;


結果為:

0 2 3 4 6 請按任意鍵繼續. . .

linq裡的其他關鍵字:

orderby

var queryLondonCustomers3 =     from cust in customers    where cust.City == "London"    orderby cust.Name ascending    select cust;

使用orderby…descending 可以相反順序(從 Z 到 A)對結果進行排序
group ... by ...

// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>  var queryCustomersByCity =      from cust in customers      group cust by cust.City;  // customerGroup is an IGrouping<string, Customer>  foreach (var customerGroup in queryCustomersByCity)  {      Console.WriteLine(customerGroup.Key);      foreach (Customer customer in customerGroup)      {          Console.WriteLine("    {0}", customer.Name);      }  }

group ... by ...按指定的鍵分組結果

join

var innerJoinQuery =    from cust in customers    join dist in distributors on cust.City equals dist.City    select new { CustomerName = cust.Name, DistributorName = dist.Name };

聯結運算建立資料來源中沒有顯式建模的序列之間的關聯。但在 LINQ 中,不必像在 SQL 中那樣頻繁使用 join,因為 LINQ 中的外鍵在物件模型中表示為包含項集合的屬性。

C# Linq

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.