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=,Name="张三",Term="第一学期",Course="Math",Score=},
new StudentScore(){ID=,Name="张三",Term="第一学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="张三",Term="第一学期",Course="English",Score=},
new StudentScore(){ID=,Name="李四",Term="第一学期",Course="Math",Score=},
new StudentScore(){ID=,Name="李四",Term="第一学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="李四",Term="第一学期",Course="English",Score=},
new StudentScore(){ID=,Name="王五",Term="第一学期",Course="Math",Score=},
new StudentScore(){ID=,Name="王五",Term="第一学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="王五",Term="第一学期",Course="English",Score=},
new StudentScore(){ID=,Name="赵六",Term="第一学期",Course="Math",Score=},
new StudentScore(){ID=,Name="赵六",Term="第一学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="赵六",Term="第一学期",Course="English",Score=},
new StudentScore(){ID=,Name="张三",Term="第二学期",Course="Math",Score=},
new StudentScore(){ID=,Name="张三",Term="第二学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="张三",Term="第二学期",Course="English",Score=},
new StudentScore(){ID=,Name="李四",Term="第二学期",Course="Math",Score=},
new StudentScore(){ID=,Name="李四",Term="第二学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="李四",Term="第二学期",Course="English",Score=},
new StudentScore(){ID=,Name="王五",Term="第二学期",Course="Math",Score=},
new StudentScore(){ID=,Name="王五",Term="第二学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="王五",Term="第二学期",Course="English",Score=},
new StudentScore(){ID=,Name="赵六",Term="第二学期",Course="Math",Score=},
new StudentScore(){ID=,Name="赵六",Term="第二学期",Course="Chinese",Score=},
new StudentScore(){ID=,Name="赵六",Term="第二学期",Course="English",Score=},
};
可以把这个数据集想象成数据库中的一个二维表格。
示例一
通常我们会把分组后得到的数据放到匿名对象中,因为分组后的数据的列不一定和原始二维表格的一致。当然要按照原有数据的格式存放也是可以的,只需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)>=
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) >= )
.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直接没什么直接关系。
.简单形式: 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。 .最大值 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。 .最小值 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。 .平均值 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值和各个分类产品中单价的平均值。 .求和 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
});
Linq中GroupBy方法的使用总结(转)的更多相关文章
- 转载Linq中GroupBy方法的使用总结
Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等. Linq中的Groupby方法也有这种功能.具体实现看代码: 假设有如下的一个数据集: public class St ...
- Linq中GroupBy方法的使用总结(转载)
from:https://www.cnblogs.com/zhouzangood/articles/4565466.html Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均 ...
- [转]Linq中GroupBy方法的使用总结
Demo模型类: public class StudentScore { public int ID { set; get; } public string Name { set; get; } pu ...
- 转载有个小孩跟我说LINQ(重点讲述Linq中GroupBy的原理及用法)
转载原出处: http://www.cnblogs.com/AaronYang/archive/2013/04/02/2994635.html 小孩LINQ系列导航:(一)(二)(三)(四)(五)(六 ...
- Linq 中 Distinct 方法扩展
原文链接 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html public static class LinqEx { publ ...
- linq 中执行方法
Database1Entities db = new Database1Entities(); protected void Page_Load(object sender, EventArgs e) ...
- 基础才是重中之重~理解linq中的groupby
linq将大部分SQL语句进行了封装,这使得它们更加面向对象了,对于开发者来说,这是一件好事,下面我从基础层面来说一下GroupBy在LINQ中的使用. 对GroupBy的多字段分组,可以看我的这篇文 ...
- C#3.0新增功能09 LINQ 基础07 LINQ 中的查询语法和方法语法
连载目录 [已更新最新开发文章,点击查看详细] 介绍性的语言集成查询 (LINQ) 文档中的大多数查询是使用 LINQ 声明性查询语法编写的.但是在编译代码时,查询语法必须转换为针对 .NET ...
- Linq 中按照多个值进行分组(GroupBy)
Linq 中按照多个值进行分组(GroupBy) .GroupBy(x => new { x.Age, x.Sex }) group emp by new { emp.Age, emp.Sex ...
随机推荐
- 【mysql】mysql统计查询count的效率优化问题
mysql统计查询count的效率优化问题 涉及到一个问题 就是 mysql的二级索引的问题,聚簇索引和非聚簇索引 引申地址:https://www.cnblogs.com/sxdcgaq8080/p ...
- 两步改动CentOS主机名称
在CentOS系统中,改动主机名称的过程例如以下: 1. 改动network文件 编辑network文件.配置例如以下: vi /etc/sysconfig/network 配置 NETWORKING ...
- python笔记6-%u60A0和\u60a0类似unicode解码
前言 有时候从接口的返回值里面获取到的是类似"%u4E0A%u6D77%u60A0%u60A0"这种格式的编码,不是python里面的unicode编码. python里面的uni ...
- ICLR 2013 International Conference on Learning Representations深度学习论文papers
ICLR 2013 International Conference on Learning Representations May 02 - 04, 2013, Scottsdale, Arizon ...
- SPSS Clementine 数据挖掘入门2
下面使用Adventure Works数据库中的Target Mail作例子,通过建立分类树和神经网络模型,决策树用来预测哪些人会响应促销,神经网络用来预测年收入. Target Mail数据在SQL ...
- centos6.x升级glibc-2.17
glibc glibc是GNU发布的libc库,即c运行库.glibc是linux系统中最底层的api,几乎其它任何运行库都会依赖于glibc:它本身也提供了许多其它一些必要功能服务的实现: libc ...
- jQuery过滤选择器:not()方法介绍
jQuery(':not(selector)') 在jQuery的早期版本中,:not()筛选器只支持简单的选择器,说明我们传入到:not这个filter中的selector可以任意复杂,比如:not ...
- Node.js:EventEmitter类
一.EventEmitter 类 Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时 ...
- Tapable 0.2.8 入门
[原文:Tapable 0.2.8 入门] tapable是webpack的核心框架(4.0以上版本的API已经发生了变化),是一个基于事件流的框架,或者叫做发布订阅模式,或观察者模式,webpack ...
- 使用BeyondCompare比较文件夹下的文件时,相同的文件内容,但显示为不相同
主要原因是: 两个文件行尾标题不一致而导致的,一个是PC,一个是Unix 解决办法: 随便比较文件夹中的两个文件,点击规则,去掉比较行尾(pc/mac/unix)选项,点击确认,回到文件夹比较界面,刷 ...