Linq 家族包含三大支柱,提供「殊途同歸」的查詢體驗:
System.Linq.Enumerable)System.Xml.Linq.dll)System.Data.Linq.dll,原生支援 SQL Server;DbLinq 擴充支援 MySQL/Oracle/PostgreSQL/SQLite)
// 查詢語法 (語法糖)
var result = from book in books
where book.Title.StartsWith("I")
orderby book.Price
select new { Key = book.Title, Value = book.Price };
// 編譯後等同方法語法
var result = books.Where(b => b.Title.StartsWith("I"))
.OrderBy(b => b.Price)
.Select(b => new { Key = b.Title, Value = b.Price });
Reflector 反編譯確認兩者生成完全相同的 IL 代碼。
IList<Book> books = new List<Book> {
new Book { Title = "Inside COM", Price = 20 },
new Book { Title = "Inside C#", Price = 100 },
new Book { Title = "Linq", Price = 120 }
};
var result = from book in books
where book.Price > 50
orderby book.Price
select new { Key = book.Title, Value = book.Price };
[Table]
public class Book
{
[Column] public string Title { get; set; }
[Column(DbType = "numeric(5,2)")] public float Price { get; set; }
[Column] public string Author { get; set; }
[Column] public string ISBN { get; set; }
}
// 查詢碼完全相同,僅資料源不同
DataContext db = new DataContext(connString);
var result = from book in db.GetTable<Book>()
where book.Price > 50
orderby book.Price
select new { Key = book.Title, Value = book.Price };

輸出結果完全一致:Inside C# 100、Linq 120。資料儲存細節對查詢邏輯完全透明,正是 Linq「語言整合查詢」的核心價值。