適用場景:分組數據,為我們查找數據縮小范圍。
說明:分配並返回對傳入參數進行分組操作後的可枚舉對象。分組;延遲
var q =
from p in db.Products
group p by p.CategoryID into g
select g;
語句描述:使用Group By按CategoryID劃分產品。
說明:from p in db.Products 表示從表中將產品對象取出來。group p by p.CategoryID into g表示對p按CategoryID字段歸類。其結果命名為g,一旦重新命名,p的作用域就結束了,所以,最後select時,只能select g。當然,也不必重新命名可以這樣寫:
var q =
from p in db.Products
group p by p.CategoryID;
我們用示意圖表示:

如果想遍歷某類別中所有記錄,這樣:
foreach (var gp in q)
{
if (gp.Key == 2)
{
foreach (var item in gp)
{
//do something
}
}
}
var q =
from p in db.Products
group p by p.CategoryID into g
select new { CategoryID = g.Key, g };
說明:在這句LINQ語句中,有2個property:CategoryID和g。這個匿名類,其實質是對返回結果集重新進行了包裝。把g的property封裝成一個完整的分組。如下圖所示:

如果想遍歷某匿名類中所有記錄,要這麼做:
foreach (var gp in q)
{
if (gp.CategoryID == 2)
{
foreach (var item in gp.g)
{
//do something
}
}
}
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MaxPrice = g.Max(p => p.UnitPrice)
};
語句描述:使用Group By和Max查找每個CategoryID的最高單價。
說明:先按CategoryID歸類,判斷各個分類產品中單價最大的Products。取出CategoryID值,並把UnitPrice值賦給MaxPrice。
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MinPrice = g.Min(p => p.UnitPrice)
};
語句描述:使用Group By和Min查找每個CategoryID的最低單價。
說明:先按CategoryID歸類,判斷各個分類產品中單價最小的Products。取出CategoryID值,並把UnitPrice值賦給MinPrice。
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
AveragePrice = g.Average(p => p.UnitPrice)
};
語句描述:使用Group By和Average得到每個CategoryID的平均單價。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品中單價的平均值。
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
TotalPrice = g.Sum(p => p.UnitPrice)
};
語句描述:使用Group By和Sum得到每個CategoryID 的單價總計。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品中單價的總和。
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count()
};
語句描述:使用Group By和Count得到每個CategoryID中產品的數量。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品的數量。
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count(p => p.Discontinued)
};
語句描述:使用Group By和Count得到每個CategoryID中斷貨產品的數量。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品的斷貨數量。 Count函數裡,使用了Lambda表達式,Lambda表達式中的p,代表這個組裡的一個元素或對象,即某一個產品。
var q =
from p in db.Products
group p by p.CategoryID into g
where g.Count() >= 10
select new {
g.Key,
ProductCount = g.Count()
};
語句描述:根據產品的―ID分組,查詢產品數量大於10的ID和產品數量。這個示例在Group By子句後使用Where子句查找所有至少有10種產品的類別。
說明:在翻譯成SQL語句時,在最外層嵌套了Where條件。
var categories =
from p in db.Products
group p by new
{
p.CategoryID,
p.SupplierID
}
into g
select new
{
g.Key,
g
};
語句描述:使用Group By按CategoryID和SupplierID將產品分組。
說明:既按產品的分類,又按供應商分類。在by後面,new出來一個匿名類。這裡,Key其實質是一個類的對象,Key包含兩個Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍歷CategoryID的值。
var categories =
from p in db.Products
group p by new { Criterion = p.UnitPrice > 10 } into g
select g;
語句描述:使用Group By返回兩個產品序列。第一個序列包含單價大於10的產品。第二個序列包含單價小於或等於10的產品。
說明:按產品單價是否大於10分類。其結果分為兩類,大於的是一類,小於及等於為另一類。