var q = from p in db.Products
group p by p.CategoryID into g
select g;
from p in db.Products:取出每個產品實體 p。group p by p.CategoryID:依 CategoryID 分群。into g:必須將分群結果重新命名為 g,此後 p 離開作用域,select 只能選 g。若省略 into g,語法簡化為:
var q = from p in db.Products
group p by p.CategoryID;
這是查詢語法中極少見的「無 select 子句」形式,編譯器隱含回傳分群物件。
啟用 db.Log = Console.Out 並單步執行 foreach 觸發查詢,Console 輸出:
-- 第一條:取得所有分群 Key
SELECT [t0].[CategoryID] AS [Key]
FROM [Products] AS [t0]
GROUP BY [t0].[CategoryID]
-- 第二條:針對每個 Key 取得明細(以 Key=1 為例)
SELECT [t0].[ProductID], [t0].[ProductName], ...
FROM [Products] AS [t0]
WHERE ((@x1 IS NULL) AND ([t0].[CategoryID] IS NULL)) OR (@x1 = [t0].[CategoryID])
-- @x1 = 1
LINQ to SQL 採用延遲載入策略:先取群組 Key,迭代時再按需載入各群組明細。這與 T-SQL 單次查詢彙總的模式截然不同。