如何使用LINQ的 Group子句
要在LINQ中使用Group子句來達到T-SQL的Group By效果,可參考下列程式碼:
- 以下程式碼從北風資料庫的Order Details資料表依照OrderID來做Group By,並計算每一Group的筆數:
1: using (NorthwindEntities context = new NorthwindEntities())
2: {
3: var query = from p in context.Order_Details
4: group p by p.OrderID into q
5: select new { cnt = q.Count(), q.Key };
6: foreach (var item in query.Where(o => o.cnt > 1))
7: {
8: Console.WriteLine(string.Format("{0},{1}", item.Key, item.cnt));
9: }
10:
11: }
其中q.Key為GroupBy條件KEY值,以本例而言就是OrderID。
- 以下程式碼為透過SQL ServerProfiler錄製上述LINQ程式所轉成的TSQL:
1: SELECT
2: [GroupBy1].[K1] AS [OrderID],
3: [GroupBy1].[A1] AS [C1]
4: FROM ( SELECT
5: [Extent1].[OrderID] AS [K1],
6: COUNT(1) AS [A1]
7: FROM [dbo].[Order Details] AS [Extent1]
8: GROUP BY [Extent1].[OrderID]
9: ) AS [GroupBy1]
10: WHERE [GroupBy1].[A1] > 1
【參考資料】