本篇介紹 LINQ 查詢表達式和一些在查詢中執行的典型操做。html
from
子句引入數據源 (customers
) 和範圍變量 (cust
) 。
// 從 IEnumerable<Customer> 中查詢全部的客戶信息 var queryAllCustomers = from cust in customers select cust;
範圍變量就像 foreach
循環中的迭代變量,但查詢表達式中不會真正發生迭代。 當執行查詢時,範圍變量將充當對 customers
中每一個連續的元素的引用。 因爲編譯器能夠推斷 cust
的類型,所以無需顯式指定它。 可經過 let
子句引入其餘範圍變量。 有關詳細信息,請參閱 let 子句。數據庫
對於非泛型數據源(例如 ArrayList),必須顯式鍵入範圍變量。 有關詳細信息,請參閱如何:使用 LINQ 查詢 ArrayList (C#) 和 from 子句。express
where
子句生成結果。 篩選器實際指定要從源序列排除哪些元素。 在下列示例中,僅返回地址位於「London」的 customers
。
var queryLondonCustomers = from cust in customers where cust.City == "London" select cust;
可以使用熟悉的 C# 邏輯 AND
和 OR
運算符,在 where
子句中根據須要應用盡量多的篩選器表達式。 例如,若要僅返回來自「London」的客戶 AND
該客戶名稱爲「Devon」,可編寫如下代碼:編程
where cust.City=="London" && cust.Name == "Devon"
要返回來自 London 或 Paris 的客戶,可編寫如下代碼:編程語言
where cust.City == "London" || cust.City == "Paris"
orderby
子句根據要排序類型的默認比較器,對返回序列中的元素排序。 例如,基於 Name
屬性,可將下列查詢擴展爲對結果排序。 因爲 Name
是字符串,默認比較器將按字母順序從 A 到 Z 進行排序。
var queryLondonCustomers3 = from cust in customers where cust.City == "London" orderby cust.Name ascending select cust;
要對結果進行從 Z 到 A 的逆序排序,請使用 orderby…descending
子句。有關詳細信息,請參閱 orderby 子句。ide
group
子句用於對根據您指定的鍵所得到的結果進行分組。 例如,可指定按 City
對結果進行分組,使來自 London 或 Paris 的全部客戶位於單獨的組內。 在這種狀況下,cust.City
是鍵。
// queryCustomersByCity 是 IEnumerable<IGrouping<string, Customer>> 類型 var queryCustomersByCity = from cust in customers group cust by cust.City; // customerGroup 是 IGrouping<string, Customer> 類型 foreach (var customerGroup in queryCustomersByCity) { Console.WriteLine(customerGroup.Key); foreach (Customer customer in customerGroup) { Console.WriteLine(" {0}", customer.Name); } }
使用 group
子句結束查詢時,結果將以列表的形式列出。 列表中的每一個元素都是具備 Key
成員的對象,列表中的元素根據該鍵被分組。 模塊化
在循環訪問生成組序列的查詢時,必須使用嵌套 foreach
循環。 外層循環循環訪問每一個組,內層循環循環訪問每一個組的成員。ui
若是必須引用某個組操做的結果,可以使用 into
關鍵字建立能被進一步查詢的標識符。 下列查詢僅返回包含兩個以上客戶的組:spa
// custQuery 是 IEnumerable<IGrouping<string, Customer>> 類型 var custQuery = from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key select custGroup;
有關詳細信息,請參閱 group 子句。code
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 中的外鍵在對象模型中表示爲包含項集合的屬性。 例如 Customer
對象包含 Order
對象的集合。 沒必要執行聯接,只需使用點表示法訪問訂單:
from order in Customer.Orders...
有關詳細信息,請參閱 join 子句。
select
子句生成查詢結果並指定每一個返回的元素的「形狀」或類型。 例如,能夠指定結果包含的是整個 Customer
對象、僅一個成員、成員的子集,仍是某個基於計算或新對象建立的徹底不一樣的結果類型。 當 select
子句生成除源元素副本之外的內容時,該操做稱爲投影 。 使用投影轉換數據是 LINQ 查詢表達式的一種強大功能。 有關詳細信息,請參閱使用 LINQ (C#) 和 select 子句進行數據轉換。