from:https://www.cnblogs.com/zhouzangood/articles/4565466.html

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,由于是要对多个字段分组的,www.it165.net 因此构建一个匿名对象,
对这个匿名对象分组,分组得到的其实是一个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);
}

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

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

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

  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. JQuery中$.ajax()方法参数详解 转载

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  6. 关于 android 中 postDelayed方法的讲解 (转载)

    转自:http://blog.csdn.net/xiabo851205/article/details/7991529 这是一种可以创建多线程消息的函数 使用方法: 1,首先创建一个Handler对象 ...

  7. Linq 中 Distinct 方法扩展

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

  8. linq 中执行方法

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

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

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

随机推荐

  1. zClip使用时ZeroClipboard生成的位置不对的问题

    zclip官网:http://steamdev.com/zclip 我之前在另外一篇博文里面写了一个解决生成的位置不对的问题,请参考:http://www.cnblogs.com/longshiyVi ...

  2. Unity异常警告错误处理方法

    原地址:http://www.haogongju.net/art/2591936 1.  The AnimationClip 'cube1_anim' used by the Animation co ...

  3. 普通用户 crontab 任务不运行

    今天发如今linux下,普通用户的crontab任务不运行.网上搜了好多.好多说要在运行的脚本前面加上例如以下内容 if [ -f ~/.bash_profile ]; then   . ~/.bas ...

  4. TP框架中模糊查询实现

    TP框架中模糊查询实现 $where['g.name'] = array('like','%'.$groupname.'%'); 表达式查询 上面的查询条件仅仅是一个简单的相等判断,可以使用查询表达式 ...

  5. ant-design 实现 添加页面

    1.逻辑代码 /** * 添加用户 */ import React,{PureComponent} from 'react' import {Card,Form,Input,Select,Button ...

  6. (六)Oracle学习笔记—— 约束

    1. 约束介绍 表虽然建立完成了,但是表中的数据是否合法并不能有所检查,而如果要想针对于表中的数据做一些过滤的话,则可以通过约束完成,约束的主要功能是保证表中的数据合法性. 按照约束的分类,一共有五种 ...

  7. Python解微分方程

    1.求解常微分方程的步骤: from sympy import * init_printing() #定义符号常量x 与 f(x) g(x).这里的f g还可以用其他字母替换,用于表示函数 x = S ...

  8. [原创]如何让freeswitch转发客户端自定义的INFO消息

    如何让freeswitch转发客户端自定义的INFO消息 英文概述: this article is about how to configure freeswitch to forward self ...

  9. MySQL 使用 比较函数 INTERVAL() 函数 实现数据按区间分组

    首先看一下它的定义: INTERVAL(N,N1,N2,N3,..........) INTERVAL()函数进行比较列表(N1,N2,N3等等)中的N值.该函数如果N<N1返回0,如果N< ...

  10. JavaScript之RegExp对象

    ECMAScript 通过 RegExp 类型来支持正则表达式.使用下面类似 Perl 的语法,就可以创建一个正则表达式 var expression = / pattern / flags ; 其中 ...