• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一个具有上进心的码农
因为一篇文章中有很多是从很多篇文章中摘取的,请恕我没有一一说明摘取出处,如果没有说明,则该文章默认是摘取,如有侵犯您的权益,请与我联系,将会马上删除。
博客园    首页    新随笔    联系   管理    订阅  订阅

LINQ to SQL语句之Group By/Having和Exists/In/Any/All/Contains

Group By/Having操作符

说明
:分配并返回对传入参数进行分组操作后的可枚举对象。分组;延迟

.简单形式:
var q =
from p in db.Products
group p by p.CategoryID into g
select g;
 
说明:from p in db.Products 表示从表中将产品对象取出来。group p by p.CategoryID into g表示对p按CategoryID字段归类。其结果命名为g,一旦重新命名,p的作用域就结束了,所以,最后select时,只能select g。

2.Select匿名类:

var q =
from p in db.Products
 

3.最大值

说明:先按CategoryID归类,判断各个分类产品中单价最大的Products。取出CategoryID值,并把UnitPrice值赋给MaxPrice。

var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MaxPrice = g.Max(p => p.UnitPrice)
};
 

4.最小值

 

说明:先按CategoryID归类,判断各个分类产品中单价最小的Products。取出CategoryID值,并把UnitPrice值赋给MinPrice。

var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
MinPrice = g.Min(p => p.UnitPrice)
};

5.平均值

说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的平均值。

var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
AveragePrice = g.Average(p => p.UnitPrice)
};
 

6.求和

 

说明:先按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)
};
 

7.计数

 

说明:先按CategoryID归类,取出CategoryID值和各个分类产品的数量。

var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count()
};
 

8.带条件计数

 

说明:先按CategoryID归类,取出CategoryID值和各个分类产品的断货数量。 Count函数里,使用了Lambda表达式,Lambda表达式中的p,代表这个组里的一个元素或对象,即某一个产品。

var q =
from p in db.Products
group p by p.CategoryID into g
select new {
g.Key,
NumProducts = g.Count(p => p.Discontinued)
};

9.Where限制

 

说明:在翻译成SQL语句时,在最外层嵌套了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和产品数量。

10.Multiple Columns

 

说明:既按产品的分类,又按供应商分类。在by后面,new出来一个匿名类。这里,Key其实质是一个类的对象,Key包含两个Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍历CategoryID的值。

var categories =
from p in db.Products
group p by new
{
p.CategoryID,
p.SupplierID
}
into g
select new
{
g.Key,
g
};

11.Expression(表达式)

 

说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。

var categories =
from p in db.Products
group p by new { Criterion = p.UnitPrice > 10 } into g
select g;

Exists/In/Any/All/Contains操作符

 

适用场景:用于判断集合中元素,进一步缩小范围

group p by p.CategoryID into g select new { CategoryID = g.Key, g };


posted @ 2008-06-19 12:02  不若相忘于江湖  阅读(262)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3