GroupBy根据多个字段分组使用方式:
一、使用扩展方法
- query.GroupBy(q => new { q.Year, q.Month })
- .Select(q => new
- {
- Year = q.Key.Year,
- Month = q.Key.Month,
- BuildAmount = q.Sum(i => i.BuildAmount),
- RecAmount = q.Sum(i => i.RecAmount),
- Amount = q.Sum(i => i.Amount),
- RealAmount = q.Sum(i => i.RealAmount)
- });
query.GroupBy(q => new { q.Year, q.Month }) .Select(q => new { Year = q.Key.Year, Month = q.Key.Month, BuildAmount = q.Sum(i => i.BuildAmount), RecAmount = q.Sum(i => i.RecAmount), Amount = q.Sum(i => i.Amount), RealAmount = q.Sum(i => i.RealAmount) });
二、Linq方式
- var query = from l in list
- group l by new { l.Name, l.BatNum } into g
- select new
- {
- Name = g.Key.Name,
- Count = g.Sum(a => a.Count),
- BatNum = g.Key.BatNum
- };
var query = from l in list group l by new { l.Name, l.BatNum } into g select new { Name = g.Key.Name, Count = g.Sum(a => a.Count), BatNum = g.Key.BatNum };
三、生成KeyValue类型
- Dictionary<string,decimal> buildList = _build.FindList().GroupBy(q => q.SaleCode)
- .Select(q => new { Code = q.Key, ReaAmount = q.Sum(i => i.RealAmount) })
- .ToDictionary(q => q.Code, q => q.ReaAmount);
1)单个字段Group by:
- //a.Key类型与a.Province字段类型一样
- .GroupBy(a => a.Province).Select(a => a.Key).ToList();
//a.Key类型与a.Province字段类型一样
.GroupBy(a => a.Province).Select(a => a.Key).ToList();
2)多个字段Group by:
- //此时返回的数据列表需要自己转换
- .GroupBy(a => new { a.Date, a.Week }).Select(a => a.Key).ToList();
//此时返回的数据列表需要自己转换
.GroupBy(a => new { a.Date, a.Week }).Select(a => a.Key).ToList();
3)单个字段Order by:
- .OrderBy(a => a.Date).ToList()
.OrderBy(a => a.Date).ToList()
4)多个字段Order by:
- .OrderBy(a => a.Date).ThenBy(a => a.EndTime).ThenBy(a => a.StartTime).ToList()
.OrderBy(a => a.Date).ThenBy(a => a.EndTime).ThenBy(a => a.StartTime).ToList()
5)多个字段Order by倒序:
- .OrderByDescending(a => a.Date).ThenByDescending(a => a.EndTime).ThenByDescending(a => a.StartTime).ToList()
.OrderByDescending(a => a.Date).ThenByDescending(a => a.EndTime).ThenByDescending(a => a.StartTime).ToList()
http://blog.csdn.net/u011127019/article/details/54943303
原文出处:http://www.itdos.com/CSharp/20150409/0153322.html