转载地址: http://www.prg-cn.com/article-4468-1.html
Group By/Having操作符
适用场景:分组数据,为我们查找数据缩小 范围。
说明:分配并返回对传入参数进行分组操作后的可枚举对象。分 组;延迟
1.简单形式:
- 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
- }
- }
- }