標籤:
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