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. http://blog.sina.com.cn/s/blog_628cc2b70102v115.html

    http://blog.sina.com.cn/s/blog_628cc2b70102v115.html

  2. 除了cPickle,cjson外还有没有更高效点的序列化库了

    除了cPickle,cjson外还有没有更高效点的序列化库了 http://blog.csdn.net/chen_lovelotus/article/details/7228745 msgpack最快 ...

  3. HTML5 Canvas 绘制库存变化折线

    <!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type&quo ...

  4. tcp/ip--百度百科

    Transmission Control Protocol/Internet Protocol的简写,中译名为传输控制协议/因特网互联协议,又名网络通讯协议,是Internet最基本的协议.Inter ...

  5. android:numColumns="auto_fit" 失效问题

    GridView 设置此属性无效:android:numColumns="auto_fit" ,请确认已经设置过 android:columnWidth="*dp&quo ...

  6. IOS 应用程序路径

    -- 获取资源文件目录 .app/下的图片,音频等资源文件 print("bundlePath" + NSBundle.mainBundle().bundlePath) //以下是 ...

  7. 符合BME风格的弹窗\菜单\表格\文件上传控件

    1.弹窗 2.菜单 3.表格 4.文件上传控件 笔记补充......

  8. SDUTOJ 2775 小P的故事——奇妙的饭卡

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvUl9NaXNheWE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA ...

  9. Atitit. C#.net clr 2.0  4.0新特性

    Atitit. C#.net clr 2.0  4.0新特性 1. CLR内部结构1 2. CLR 版本发展史3 3. CLR 2.0 3 4. CLR 4 新特性 概览4 4.1.1.  托管与本地 ...

  10. 浅谈C语言中断处理机制

    一.中断机制 1.实现中断响应和中断返回 当CPU收到中断请求后,能根据具体情况决定是否响应中断,如果CPU没有更急.更重要的工作,则在执行完当前指令后响应这一中断请求.CPU中断响应过程如下:首先, ...