在LINQ中对多个独立列求和
本文关键字:独立 求和 LINQ | 更新日期: 2023-09-27 18:15:07
有人知道如何正确有效地对多个列求和吗?
我有一个庞大的连接查询
db.myTable.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Where(...)
我现在需要做的是sum列A, B, C和d和Count e
所以我有一个记录,里面有总和
我尝试使用group by和Select(x => new myClass{A => x.})
下面是MAJORLY efficient
myClass mine = new myClass{
Number = myList.GroupBy(x => x.u.ID).Count(),
Area = myList.Sum(a => a.u.Area ?? 0),
Rent = myList.Sum(a => a.r.Rent ?? 0) ,
ERV = myList.Sum(a => a.e.ERV ?? 0)
};
下面是有效率的,但只对第一组求和…
myClass mine = (from p in myList
group p by p.u.ID into g
select new myClass
{
Number = g.Count(),
Area = g.Sum(a => a.u.Area ?? 0),
Rent = g.Sum(a => a.r.Rent ?? 0) ,
ERV = g.Sum(a => a.e.ERV ?? 0)
}).FirstOrDefault();
我认为您正试图获得数字字段的Distinct Count()
与未分组的 Sum()
在单个记录中的其他字段。
var mine = (from x in (from p in mc
group p by p.u.id into g1
select new {
Number = g1.Count(),
Area = g1.Sum(a => a.u.Area??0),
Rent = g1.Sum(a => a.u.Rent??0),
ERV = g1.Sum(a => a.e.ERV ?? 0)
})
group x by 1 into g2
select new myClass {
Number = g2.Count(),
Area = g2.Sum(a => a.Area),
Rent = g2.Sum(a => a.Rent),
ERV = g2.Sum(a => a.ERV)
}).FirstOrDefault();