Linq中的group by多表多字段,Sum求和
//Line to Sql 写法
var data = (from a in Items group a by new { a.GroupId, a.Id } into b //orderby new ComparerItem() { GroupId = b.Key.GroupId, Id = b.Key.Id } descending
.where(o => o.Id>1000) select new { GroupId = b.Key.GroupId, Id = b.Key.Id, Count = b.Sum(c => c.Count), Weight = b.Sum(c => c.Weight) }).OrderBy(t => t.GroupId).ThenBy(t => t.Id);
items 是一个包含4个字段(GroupId, Id, Count, Weight)的list.
效果,按GroupId,Id 分组 ,并统计Count字段和Weight字段
//labmda 写法 var data = items.GroupBy( t=> t.GroupBy,t=> t.Id) .where( f=> f.Id>1000) .Select( g=> new { GroupId = g.GroupId, Id = g.Id, Count = g.Count( ), SumWeight = g.Sum( x=>x.Weight) } );
//多表写法 from a in TableA join b in TableB on a.Id equals b.aId where ((b.Type == 1 || b.Type == 2 || b.Type == 5) && b.State == 1) group new { a.Id, b.Name,b,CreateDate } by new { a.Id, b.Name } into g select (new Class1 { Id = g.Key.Id, Name = g.Key.Name ?? "" }); class Class1 { public int Id { get; set; } publid string Name { get; set; } }
from c in Customers join p in Purchases on c.ID equals p.CustomerID group p.Price by new { p.Date.Year, c.Name } into salesByYear orderby salesByYear.Key.Year descending select new { TotalPrice= salesByYear.Sum(), Year=salesByYear.Key.Year, Name=salesByYear.Key.Name }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)