Linq中GroupBy方法的使用总结(转)

Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等。

Linq中的Groupby方法也有这种功能。具体实现看代码:

假设有如下的一个数据集:

public class StudentScore 
    { 
        public int ID { set; get; } 
        public string Name { set; get; } 
        public string Course { set; get; } 
        public int Score { set; get; } 
        public string Term { set; get; } 
    } 
List<StudentScore> lst = new List<StudentScore>() { 
                new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="Math",Score=80}, 
                new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="Chinese",Score=90}, 
                new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="English",Score=70}, 
                new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="Math",Score=60}, 
                new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="Chinese",Score=70}, 
                new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="English",Score=30}, 
                new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="Math",Score=100}, 
                new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="Chinese",Score=80}, 
                new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="English",Score=80}, 
                new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="Math",Score=90}, 
                new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="Chinese",Score=80}, 
                new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="English",Score=70}, 
                new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="Math",Score=100}, 
                new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="Chinese",Score=80}, 
                new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="English",Score=70}, 
                new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="Math",Score=90}, 
                new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="Chinese",Score=50}, 
                new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="English",Score=80}, 
                new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="Math",Score=90}, 
                new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="Chinese",Score=70}, 
                new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="English",Score=80}, 
                new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="Math",Score=70}, 
                new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="Chinese",Score=60}, 
                new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="English",Score=70}, 
            }; 

可以把这个数据集想象成数据库中的一个二维表格。

示例一

通常我们会把分组后得到的数据放到匿名对象中,因为分组后的数据的列不一定和原始二维表格的一致。当然要按照原有数据的格式存放也是可以的,只需select的时候采用相应的类型即可。

第一种写法很简单,只是根据下面分组。

//分组,根据姓名,统计Sum的分数,统计结果放在匿名对象中。两种写法。 
//第一种写法 
Console.WriteLine("---------第一种写法"); 
var studentSumScore_1 = (from l in lst 
                         group l by l.Name into grouped 
                         orderby grouped.Sum(m => m.Score) 
                         select new { Name = grouped.Key, Scores = grouped.Sum(m => m.Score) }).ToList(); 
foreach (var l in studentSumScore_1) 
{ 
    Console.WriteLine("{0}:总分{1}", l.Name, l.Scores); 
} 
第二种写法和第一种其实是等价的。 
//第二种写法 
Console.WriteLine("---------第二种写法"); 
var studentSumScore_2 = lst.GroupBy(m => m.Name) 
    .Select(k => new { Name = k.Key, Scores = k.Sum(l => l.Score) }) 
    .OrderBy(m => m.Scores).ToList(); 
foreach (var l in studentSumScore_2) 
{ 
    Console.WriteLine("{0}:总分{1}", l.Name, l.Scores); 
} 

示例二

当分组的字段是多个的时候,通常把这多个字段合并成一个匿名对象,然后group by这个匿名对象。

注意:groupby后将数据放到grouped这个变量中,grouped 其实是IGrouping<TKey, TElement>类型的,IGrouping<out TKey, out TElement>继承了IEnumerable<TElement>,并且多了一个属性就是Key,这个Key就是当初分组的关键字,即那些值都相同的字段,此处就是该匿名对象。可以在后续的代码中取得这个Key,便于我们编程。

orderby多个字段的时候,在SQL中是用逗号分割多个字段,在Linq中就直接多写几个orderby。

//分组,根据2个条件学期和课程,统计各科均分,统计结果放在匿名对象中。两种写法。 
Console.WriteLine("---------第一种写法"); 
var TermAvgScore_1 = (from l in lst 
                      group l by new { Term = l.Term, Course = l.Course } into grouped 
                      orderby grouped.Average(m => m.Score) ascending 
                      orderby grouped.Key.Term descending 
                      select new { Term = grouped.Key.Term, Course = grouped.Key.Course, Scores = grouped.Average(m => m.Score) }).ToList(); 
foreach (var l in TermAvgScore_1) 
{ 
    Console.WriteLine("学期:{0},课程{1},均分{2}", l.Term, l.Course, l.Scores); 
} 
Console.WriteLine("---------第二种写法"); 
var TermAvgScore_2 = lst.GroupBy(m => new { Term = m.Term, Course = m.Course }) 
    .Select(k => new { Term = k.Key.Term, Course = k.Key.Course, Scores = k.Average(m => m.Score) }) 
    .OrderBy(l => l.Scores).OrderByDescending(l => l.Term); 
foreach (var l in TermAvgScore_2) 
{ 
    Console.WriteLine("学期:{0},课程{1},均分{2}", l.Term, l.Course, l.Scores); 
} 

示例三

Linq中没有SQL中的Having语句,因此是采用where语句对Group后的结果过滤。 

//分组,带有Having的查询,查询均分>80的学生 
Console.WriteLine("---------第一种写法"); 
var AvgScoreGreater80_1 = (from l in lst 
                  group l by new { Name = l.Name, Term = l.Term } into grouped 
                  where grouped.Average(m => m.Score)>=80 
                  orderby grouped.Average(m => m.Score) descending 
                  select new { Name = grouped.Key.Name, Term = grouped.Key.Term, Scores = grouped.Average(m => m.Score) }).ToList(); 
foreach (var l in AvgScoreGreater80_1) 
{ 
    Console.WriteLine("姓名:{0},学期{1},均分{2}", l.Name, l.Term, l.Scores); 
} 
Console.WriteLine("---------第二种写法"); 
//此写法看起来较为复杂,第一个Groupby,由于是要对多个字段分组的,因此构建一个匿名对象,
对这个匿名对象分组,分组得到的其实是一个IEnumberable<IGrouping<匿名类型,StudentScore>>这样一个类型。
Where方法接受,和返回的都同样是IEnumberable<IGrouping<匿名类型,StudentScore>>类型,
其中Where方法签名Func委托的类型也就成了Func<IGrouping<匿名类型,StudentScore>,bool>,
之前说到,IGrouping<out TKey, out TElement>继承了IEnumerable<TElement>,
因此这种类型可以有Average,Sum等方法。 
var AvgScoreGreater80_2 = lst.GroupBy(l => new { Name = l.Name, Term = l.Term }) 
    .Where(m => m.Average(x => x.Score) >= 80) 
    .OrderByDescending(l=>l.Average(x=>x.Score)) 
    .Select(l => new { Name = l.Key.Name, Term = l.Key.Term, Scores = l.Average(m => m.Score) }).ToList(); 
foreach (var l in AvgScoreGreater80_2) 
{ 
    Console.WriteLine("姓名:{0},学期{1},均分{2}", l.Name, l.Term, l.Scores); 
}  

原文:http://cnn237111.blog.51cto.com/2359144/1110587

group by与order by同时使用
SELECT [col1] ,[col2],MAX([col3]) FROM [tb] GROUP BY [col1] ,[col2] ORDER BY [col1] ,[col2] ,MAX([col3]) 
SELECT [col1] ,[col2],MAX([col3]) AS [col3] FROM [tb] GROUP BY [col1] ,[col2] ORDER BY [col1] ,[col2] ,[col3] 
SELECT [col1] ,[col2] FROM [tb] GROUP BY [col1] ,[col2] ,[col3] ORDER BY [col1] ,[col2] ,[col3] 

撇开聚合函数不说,select后面的列+order by后面的列必须在group by里面(sqlserver 要求,mysql 貌似没这么要求),也就是说select和order by 后面的列是group by列的子集
而select 和order by直接没什么直接关系。

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) };
var allPropertyList = PropertyList.GroupBy(
                        x => new { x.Type, x.Code},
                        (key, values) =>
                        {
                            var propertyEntities = values as PropertyEntity[] ?? values.ToArray();
                            return new PropertyEntity()
                            {
                                Type= key.Type,
                                GoodsCode = key.GoodsCode,                             
                                Code = PropertyEntities.FirstOrDefault()?.Code
                               
                            };
                        }).ToList();
var param = models.GroupBy(m => m.Key, (key, values) => new
            {
                StockId = key,
                StockOutAmount = values.Sum(g => g.Value),
                ModifyBy = user.Name
            });
使用group by 对筛选后的结果进行分组 使用having字句对分组后的结果进行筛选
需要注意having和where的用法区别:
1.having只能用在group by之后,对分组后的结果进行筛选(即使用having的前提条件是分组)。
2.where肯定在group by 之前
3.where后的条件表达式里不允许使用聚合函数,而having可以。
四、当一个查询语句同时出现了where,group by,having,order by的时候,执行顺序和编写顺序是:
1.执行where xx对全表数据做筛选,返回第1个结果集。
2.针对第1个结果集使用group by分组,返回第2个结果集。
3.针对第2个结果集中的每1组数据执行select xx,有几组就执行几次,返回第3个结果集。
4.针对第3个结集执行having xx进行筛选,返回第4个结果集。
5.针对第4个结果集排序。
 

注意:

     使用group by的SQL语句中,select中返回的字段,必须满足以下两个条件之一:   

      1.包含在group by语句的后面,作为分组的依据;

      2.这些字段包含在聚合函数中

原文地址:https://www.cnblogs.com/shy1766IT/p/7277069.html