查詢表達式由 from、where、orderby、select 等子句組成,編譯器將其翻譯為標準查詢運算子 (擴展方法) 調用。
string[] words = { "adobe", "excel", "acer", "query", "async", "xianfen", "apple", "amazon", "player", "best", "wow" };
// 查詢語法
var result = from w in words
where w.StartsWith("a")
orderby w descending
select w;
// 輸出: async, apple, amazon, adobe, acer
// 1. 查詢語法 (語法糖)
var q1 = from w in words where w.StartsWith("a") orderby w descending select w;
// 2. 擴展方法鏈 (編譯器生成)
var q2 = words.Where(w => w.StartsWith("a")).OrderByDescending(w => w);
// 3. 靜態方法調用 (最原始形式)
var q3 = Enumerable.OrderByDescending(
Enumerable.Where(words, w => w.StartsWith("a")),
w => w);
結論:查詢語法純粹是語法糖,運行時仍是 .NET 2.0 CLR,IL 完全一致。
| 程序集 | 命名空間/類型 | 用途 |
|---|---|---|
| System.Core.dll | System.Linq.Enumerable, IQueryable, IGrouping... | LINQ to Objects 核心 |
| System.Data.DataSetExtensions.dll | DataTableExtensions, DataRowExtensions | LINQ to DataSet |
| System.Data.Linq.dll | DataContext, Table<T>, IQueryable | LINQ to SQL |
| System.Xml.Linq.dll | XElement, XDocument, XAttribute | LINQ to XML |
public class Student { public int Id; public string Name;
public override string ToString() => $"Student ID:{Id},Name:{Name}"; }
public class Course { public int Id; public string Name;
public override string ToString() => $"Course ID:{Id},Name:{Name}"; }
public class Score { public int StudentId; public int CourseId; public double Value;
public override string ToString() => $"StudentID:{StudentId},CourseID:{CourseId},Score:{Value}"; }
public static class DataSource
{
public static List<Student> Students { get; } = new List<Student> {
new Student{Id=1,Name="Andy"}, new Student{Id=2,Name="Bill"},
new Student{Id=3,Name="Cindy"}, new Student{Id=4,Name="Dark"} };
public static List<Student> Students2 { get; } = new List<Student> {
new Student{Id=5,Name="Erik"}, new Student{Id=6,Name="Frank"} };
public static List<Course> Courses { get; } = new List<Course> {
new Course{Id=1,Name="C語言"}, new Course{Id=2,Name="生物物理"},
new Course{Id=3,Name="編譯原理"}, new Course{Id=4,Name="財務"},
new Course{Id=5,Name="大學英語"} };
public static List<Score> Scores { get; } = new List<Score> {
new Score{StudentId=1,CourseId=1,Value=78}, new Score{StudentId=1,CourseId=2,Value=60},
new Score{StudentId=1,CourseId=3,Value=92}, new Score{StudentId=1,CourseId=4,Value=85},
new Score{StudentId=1,CourseId=5,Value=55.5}, new Score{StudentId=2,CourseId=1,Value=59},
new Score{StudentId=2,CourseId=2,Value=78}, new Score{StudentId=2,CourseId=3,Value=86},
new Score{StudentId=3,CourseId=2,Value=60}, new Score{StudentId=4,CourseId=4,Value=96},
new Score{StudentId=5,CourseId=5,Value=78} };
}
| 子句 | 對應擴展方法 | 說明 |
|---|---|---|
| from | SelectMany (多 from) / 無 (單 from) | 指定數據源與範圍變量 |
| where | Where | 篩選條件 |
| orderby | OrderBy / OrderByDescending | 排序,支援 ThenBy |
| select | Select | 投影結果形狀 |
| group by | GroupBy | 分組 |
| into | 續接上一步結果 | 讓分組/連接結果繼續查詢 |
| join | Join / GroupJoin | 內連接/分組連接 |
| let | Select (引入中間變量) | 在查詢中定義臨時變量 |
理解語法糖本質,能在除錯時直接看懂 IL/方法鏈,也能靈活選擇查詢語法或方法語法。