zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# linq group by

c# by group LinQ
2023-09-14 09:16:28 时间

好久不用,忘了 记一下

//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),
          };
		};                                          

var cls = from x in db.TableNames.Select(x => x.type).Distinct().ToList()
	      select new {  account  = x?.Trim() 			

在这里插入图片描述

var cls = from x in db.TableNames.Select(x=>x.Type).Distinct().ToList()
		  group x by new {x}
		  into g 
		  select new {account=g.Key};

在这里插入图片描述