查詢運算式提供類 SQL 的宣告式語法,編譯器將其純語法轉譯為方法呼叫鏈,不綁定特定資料來源(記憶體集合、SQL、XML、自訂提供者)。
from c in customers
where c.City == "London"
orderby c.Name
select new { c.Name, c.Phone }
from:定義範圍變數與資料來源where:篩選條件orderby:排序select/group:投影或分組into:查詢延續(子查詢)| 查詢子句 | 對應方法 | 說明 |
|---|---|---|
where | Where | Lambda 述詞篩選 |
select | Select | 投影轉換 |
group ... by | GroupBy | 分組,產生 IGrouping<K,T> |
orderby | OrderBy/ThenBy | 主要/次要排序 |
orderby ... descending | OrderByDescending/ThenByDescending | 遞減排序 |
多重 from | SelectMany | 扁平化/交叉聯結 |
into | 巢狀查詢 | 前一查詢結果作為下一查詢來源 |
from c in customers where c.City == "London" select c.Name
// 翻譯
customers.Where(c => c.City == "London").Select(c => c.Name)
from c in customers group c.Name by c.Country
// 翻譯
customers.GroupBy(c => c.Country, c => c.Name)
from c in customers orderby c.Country, c.Balance descending select c
// 翻譯
customers.OrderBy(c => c.Country).ThenByDescending(c => c.Balance)
from c in customers
from o in c.Orders
where o.Date.Year == 2005
select new { c.Name, o.Id }
// 翻譯
customers.SelectMany(c => c.Orders.Where(o => o.Date.Year == 2005)
.Select(o => new { c.Name, o.Id }))
from c in customers group c by c.Country into g
select new { Country = g.Key, Count = g.Count() }
// 翻譯
customers.GroupBy(c => c.Country)
.Select(g => new { Country = g.Key, Count = g.Count() })
型別實作下列方法即支援查詢運算式(可為實例方法或擴充方法):
delegate R Func<A, R>(A arg);
class C<T> {
public C<T> Where(Func<T, bool> predicate);
public C<S> Select<S>(Func<T, S> selector);
public C<S> SelectMany<S>(Func<T, C<S>> selector);
public O<T> OrderBy<K>(Func<T, K> keySelector);
public O<T> OrderByDescending<K>(Func<T, K> keySelector);
public C<G<K, T>> GroupBy<K>(Func<T, K> keySelector);
public C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector);
}
class O<T> : C<T> {
public O<T> ThenBy<K>(Func<T, K> keySelector);
public O<T> ThenByDescending<K>(Func<T, K> keySelector);
}
class G<K, T> {
public K Key { get; }
public C<T> Group { get; }
}
Func 或 Expression<Func>(Lambda 兩者皆可轉換)ThenBy 僅能接在 OrderBy 後GroupBy 回傳擁有 Key/Group 的序列System.Linq.Enumerable 提供針對 IEnumerable<T> 的參考實作,涵蓋所有模式方法,並擴充大量實用運算子(Distinct、Join、Aggregate 等)。
q1 into x q2 → from x in (q1) q2from g1, g2 → from g1 from g2from x in e where f → from x in (e).Where(x => f)OrderBy/ThenBy 後再 Select 還原(e).SelectMany(x => from ... select v)(e).Select(x => v)(若 v==x 則簡化為 (e))(e).GroupBy(x => g, x => v)(e).OrderBy(...).Select/GroupBy(...)查詢運算式是 C# 語言整合查詢的核心表達形式,理解其翻譯機制與模式契約,不僅能寫出高效 LINQ,更能建構自訂查詢提供者(如 ORM、雲端 API 封裝)。