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
    }    
复制代码

 

posted @   szlailai  阅读(12457)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示