1.简单形式:
var q =
from p in db.Products
group p by p.CategoryID into g
select g;
语句描述:Linq使用Group By
按CategoryID
划分产品。
说明:from p in db.Products
表示从表中将产品对象取出来。group p by p.CategoryID into g
表示对p
按CategoryID
字段归类。其结果命名为g
,一旦重新命名,p
的作用域就结束了,所以,最后select
时,只能select g
。
2.最大值
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MaxPrice = g.Max(p => p.UnitPrice)
};
语句描述:Linq
使用Group By
和Max
查找每个CategoryID
的最高单价。
说明:先按CategoryID
归类,判断各个分类产品中单价最大的Products
。取出CategoryID
值,并把UnitPrice
值赋给MaxPrice
。
3.最小值
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MinPrice = g.Min(p => p.UnitPrice)
};
语句描述:Linq
使用Group By
和Min
查找每个CategoryID
的最低单价。
说明:先按CategoryID
归类,判断各个分类产品中单价最小的Products
。取出CategoryID
值,并把UnitPrice
值赋给MinPrice
。
4.平均值
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
AveragePrice = g.Average(p => p.UnitPrice)
};
语句描述:Linq
使用Group By
和Average
得到每个CategoryID
的平均单价。
说明:先按CategoryID
归类,取出CategoryID
值和各个分类产品中单价的平均值。
5.求和
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
TotalPrice = g.Sum(p => p.UnitPrice)
};
6.计数
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count()
};
语句描述:Linq使用Group By
和Count
得到每个CategoryID
中产品的数量。
说明:先按CategoryID
归类,取出CategoryID
值和各个分类产品的数量。
7.带条件计数
var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count(p => p.Discontinued)
};
语句描述:Linq使用Group By
和Count
得到每个CategoryID
中断货产品的数量。
说明:先按CategoryID
归类,取出CategoryID
值和各个分类产品的断货数量。 Count
函数里,使用了Lambda
表达式,Lambda
表达式中的p
,代表这个组里的一个元素或对象,即某一个产品。
8.Where
限制
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
条件。
9.多列(Multiple Columns
)
var categories =
from p in db.Products
group p by new
{
p.CategoryID,
p.SupplierID
}
into g
select new
{
g.Key,
g
};
语句描述:Linq使用Group By
按CategoryID
和SupplierID
将产品分组。
说明:既按产品的分类,又按供应商分类。在by
后面,new
出来一个匿名类。这里,Key
其实质是一个类的对象,Key
包含两个Property
:CategoryID
、SupplierID
。用g.Key.CategoryID
可以遍历CategoryID
的值。
10.表达式(Expression
)
var categories =
from p in db.Products
group p by new { Criterion = p.UnitPrice > 10 } into g
select g;
语句描述:Linq
使用Group By
返回两个产品序列。第一个序列包含单价大于10的产品。第二个序列包含单价小于或等于10的产品。
说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。