欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# linq group by

程序员文章站 2022-07-04 10:20:00
...

好久不用,忘了 记一下

//get data from db 
List<ModelClass> source = new List<ModelClass>();
//单一条件分组
var sc1 = from sf in source
          group sf by sf.Name;

//多个条件分组
var sc2 = from sf in source
          group sf by new { sf.Name,sf.Price,sf.Amount}
          into g
          select new 
          { 
          		Name= g.Key.Name,
          		Price= g.Sum(p=>p.Price),
          		Amount = g.Sum(p=>p.Amount)
          };

//多个条件分组,并返回新的对象
var sc3 = from sf in source
          group sf by new { sf.Name }
          into g
          //select new { Name = g.Key.Name, Price = g.Sum(p => p.Price), Amount = g.Sum(p => p.Amount) };
          select new ModelClass() 
          { 
              Name = g.Key.Name,
              Price =g.Sum(p=>p.Price),
              Number = g.Sum(p=>p.Number),
          };

相关标签: C# c#