linq中group by

本文导读:LINQ定义了大约40个查询操做符,如select、from、in、where、group 以及order by,借助于LINQ技术,咱们可使用一种相似SQL的语法来查询任何形式的数据。Linq有不少值得学习的地方,这里咱们主要介绍Linq使用Group By。html

1、Linq对谁适用学习

linq的语法经过System.Linq下面的Enumerable类提供支持,经过观察他的签名,你就会发现他为IEnumerable<T>实现了一系列的扩展方法,也就是说,只要是实现了IEnumerable<T>的对象均可以使用Linq的语法来查询。spa

 

2、Linq中的关键字.net

在ASP.NET中,为Linq引入了一些新的关键字,他们是:翻译

from join where group into let orderby select3d

熟悉Sql的同窗看着是否是有些眼熟呢,其实在Linq中他们的涵义和在SQL中相似的,因此会很容易理解的。htm

 

3、下面介绍Linq使用Group By的常见场景对象

 

1.简单形式:ip

 
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.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条件。

 

7.多列(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的值。

 

8.表达式(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分类。其结果分为两类,大于的是一类,小于及等于为另外一类。

 

 转自http://www.studyofnet.com/news/397.html