光腳丫學LINQ 002 篩選資料

2021-08-25 09:16:29 字數 898 閱讀 8671

也許最常用的查詢操作是應用布林表示式形式的篩選器。此篩選器使查詢只返回那些表示式結果為 true 的元素。使用 where 子句生成結果。實際上,篩選器指定從源序列中排除哪些元素。在下面的示例中,只返回那些位址位於倫敦的 customers。

northwinddatacontext db = new northwinddatacontext(); var londoncustomers = from customer in db.customers where customer.city == "london" select customer; foreach (var customer in londoncustomers) ", customer.customerid); console.writeline("customer name : ", customer.contactname); console.writeline("city : ", customer.city); }

您可以使用熟悉的 c# 邏輯 and 和 or 運算子來根據需要在 where 子句中應用任意數量的篩選表示式。例如,若要只返回位於「倫敦」and 姓名為「thomas hardy」的客戶,您應編寫下面的**:

var londoncustomers = from customer in db.customers where customer.city == "london" && customer.contactname == "thomas hardy" select customer;

若要返回位於倫敦或巴黎的客戶,您應編寫下面的**:

var londoncustomers = from customer in db.customers where customer.city == "london" || customer.city == "paris" select customer;

光腳丫學LINQ 006 投影

select 子句生成查詢結果並指定每個返回的元素的 形狀 或型別。例如,您可以指定結果包含的是整個 customer 物件 僅乙個成員 成員的子集,還是某個基於計算或新物件建立的完全不同的結果型別。當 select 子句生成除源元素副本以外的內容時,該操作稱為 投影 使用投影轉換資料是 linq ...

光腳丫學LINQ 004 分組資料

使用 group 子句,您可以按指定的鍵分組結果。例如,您可以指定結果應按 city 分組,以便位於倫敦或巴黎的所有客戶位於各自組中。在本例中,customer.city是鍵。在使用 group 子句結束查詢時,結果採用列表的列表形式。列表中的每個元素是乙個具有 key 成員及根據該鍵分組的元素列表...

光腳丫學LINQ 004 分組資料

使用 group 子句,您可以按指定的鍵分組結果。例如,您可以指定結果應按 city 分組,以便位於倫敦或巴黎的所有客戶位於各自組中。在本例中,customer.city是鍵。northwinddatacontext db new northwinddatacontext var allcustom...