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

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

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

  1. public class StudentScore
  2. {
  3. public int ID { set; get; }
  4. public string Name { set; get; }
  5. public string Course { set; get; }
  6. public int Score { set; get; }
  7. public string Term { set; get; }
  8. }
  9. List<StudentScore> lst = new List<StudentScore>() {
  10. new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="Math",Score=80},
  11. new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="Chinese",Score=90},
  12. new StudentScore(){ID=1,Name="张三",Term="第一学期",Course="English",Score=70},
  13. new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="Math",Score=60},
  14. new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="Chinese",Score=70},
  15. new StudentScore(){ID=2,Name="李四",Term="第一学期",Course="English",Score=30},
  16. new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="Math",Score=100},
  17. new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="Chinese",Score=80},
  18. new StudentScore(){ID=3,Name="王五",Term="第一学期",Course="English",Score=80},
  19. new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="Math",Score=90},
  20. new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="Chinese",Score=80},
  21. new StudentScore(){ID=4,Name="赵六",Term="第一学期",Course="English",Score=70},
  22. new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="Math",Score=100},
  23. new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="Chinese",Score=80},
  24. new StudentScore(){ID=1,Name="张三",Term="第二学期",Course="English",Score=70},
  25. new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="Math",Score=90},
  26. new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="Chinese",Score=50},
  27. new StudentScore(){ID=2,Name="李四",Term="第二学期",Course="English",Score=80},
  28. new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="Math",Score=90},
  29. new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="Chinese",Score=70},
  30. new StudentScore(){ID=3,Name="王五",Term="第二学期",Course="English",Score=80},
  31. new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="Math",Score=70},
  32. new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="Chinese",Score=60},
  33. new StudentScore(){ID=4,Name="赵六",Term="第二学期",Course="English",Score=70},
  34. };

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

示例一

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

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

  1. //分组,根据姓名,统计Sum的分数,统计结果放在匿名对象中。两种写法。
  2. //第一种写法
  3. Console.WriteLine("---------第一种写法");
  4. var studentSumScore_1 = (from l in lst
  5. group l by l.Name into grouped
  6. orderby grouped.Sum(m => m.Score)
  7. select new { Name = grouped.Key, Scores = grouped.Sum(m => m.Score) }).ToList();
  8. foreach (var l in studentSumScore_1)
  9. {
  10. Console.WriteLine("{0}:总分{1}", l.Name, l.Scores);
  11. }
  12. 第二种写法和第一种其实是等价的。
  13. //第二种写法
  14. Console.WriteLine("---------第二种写法");
  15. var studentSumScore_2 = lst.GroupBy(m => m.Name)
  16. .Select(k => new { Name = k.Key, Scores = k.Sum(l => l.Score) })
  17. .OrderBy(m => m.Scores).ToList();
  18. foreach (var l in studentSumScore_2)
  19. {
  20. Console.WriteLine("{0}:总分{1}", l.Name, l.Scores);
  21. }

示例二

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

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

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

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

示例三

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

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

转载Linq中GroupBy方法的使用总结的更多相关文章

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

    from:https://www.cnblogs.com/zhouzangood/articles/4565466.html Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均 ...

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

    Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等. Linq中的Groupby方法也有这种功能.具体实现看代码: 假设有如下的一个数据集: public class St ...

  3. [转]Linq中GroupBy方法的使用总结

    Demo模型类: public class StudentScore { public int ID { set; get; } public string Name { set; get; } pu ...

  4. 转载有个小孩跟我说LINQ(重点讲述Linq中GroupBy的原理及用法)

    转载原出处: http://www.cnblogs.com/AaronYang/archive/2013/04/02/2994635.html 小孩LINQ系列导航:(一)(二)(三)(四)(五)(六 ...

  5. [转载]LINQ 中的 select

    下面通过一些例子来说明怎样使用select,参考自:LINQ Samples 1.  可以对查询出来的结果做一些转换,下面的例子在数组中查找以"B"开头的名字,然后全部转成小写输出 ...

  6. Linq 中 Distinct 方法扩展

    原文链接 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html public static class LinqEx { publ ...

  7. linq 中执行方法

    Database1Entities db = new Database1Entities(); protected void Page_Load(object sender, EventArgs e) ...

  8. 基础才是重中之重~理解linq中的groupby

    linq将大部分SQL语句进行了封装,这使得它们更加面向对象了,对于开发者来说,这是一件好事,下面我从基础层面来说一下GroupBy在LINQ中的使用. 对GroupBy的多字段分组,可以看我的这篇文 ...

  9. C#3.0新增功能09 LINQ 基础07 LINQ 中的查询语法和方法语法

    连载目录    [已更新最新开发文章,点击查看详细] 介绍性的语言集成查询 (LINQ) 文档中的大多数查询是使用 LINQ 声明性查询语法编写的.但是在编译代码时,查询语法必须转换为针对 .NET ...

随机推荐

  1. 第一章、关于SQL Server数据库的备份和还原(sp_addumpdevice、backup、Restore)

    在sql server数据库中,备份和还原都只能在服务器上进行,备份的数据文件在服务器上,还原的数据文件也只能在服务器上,当在非服务器的机器上启动sql server客户端的时候,也可以通过该客户端来 ...

  2. Oracle导入(imp )与导出(exp )

    导出exp username/password@orcl file=db.dmp 导入imp username/password@orcl file=h:\db.dmp  full=y 备注:在导入之 ...

  3. log4cxx在linux下的编译和使用

    [下载] [编译动态库] [使用动态库]

  4. Android的Handler几种常见的传值方式

    public class handlerThread2 extends Activity { @Override protected void onCreate(Bundle savedInstanc ...

  5. autocapticalize和autocorrect

    首字母自动大写autocapitalize 在 iOS 中,用户可以手动开启「首字母自动大写」功能,这样输入英文的时候,首字母便会自动大写.但是,有些时候并不希望一直是首字母大写的.比如用户名这个字段 ...

  6. log file sync

    Recently, our application system has updated one app. I receive a email of complain the db server ch ...

  7. Upload/download/UrlConnection/URL

    文件上传的核心点 1:用<input type=”file”/> 来声明一个文件域.File:_____ <浏览>. 2:必须要使用post方式的表单. 3:必须设置表单的类型 ...

  8. oracle时间加减的语句写法

    FROM: http://soft.doit.com.cn/article/2012/0105/2850851.shtml --加法 --加1年  SELECT SYSDATE,ADD_MONTHS( ...

  9. R12 - OM改进了对成本与收入确认的流程

    我们知道在企业经营活动中,根据财务制度的要求,对于收入与成本确认有很复杂的原则,这里就不去细讨论这些原则了,要了解的话可以看纵横四海的BLOG: 中也有,但11中是灰的. 这个科目什么时候发挥作用呢? ...

  10. C++ 类的内存分布

    C++类内存分布 转自:http://www.cnblogs.com/jerry19880126/p/3616999.html   先写下总结,通过总结下面的例子,你就会明白总结了. 下面总结一下: ...