如何在LINQ中不使用group.Sum()实现分组求和?
不用
grp.Sum()实现相同分组求和的方案 当然可以实现!你可以借助LINQ的Aggregate方法手动完成分组内的数值累加,完全替代Sum的功能。它的核心思路就是遍历分组里的每一项,逐步把对应字段的值累加起来,和Sum的底层逻辑其实是类似的,只是更“手动”一点。
下面是修改后的完整代码:
from item in (await VehicleReplaceCostDataAsync()) group item by (item.type, item.size, item.ADA, item.eseq) into grp orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA) select new VehicleReplacementCost { type = grp.Key.type, size = grp.Key.size, ADA = grp.Key.ADA, count = grp.Aggregate(0, (total, currentItem) => total + currentItem.count), cost = grp.Aggregate(0m, (total, currentItem) => total + currentItem.cost), // 如果cost是decimal类型用0m Fcount = grp.Aggregate(0, (total, currentItem) => total + currentItem.Fcount), Fcost = grp.Aggregate(0m, (total, currentItem) => total + currentItem.Fcost), // 同理根据类型调整初始值 eseq = grp.Key.eseq, }).ToList();
小说明:
Aggregate的第一个参数是累加的初始值:如果是整数类型(比如count、Fcount)用0,如果是小数类型(比如cost、Fcost)记得用0m来匹配decimal类型,避免隐式转换问题。- 第二个参数是累加器函数,
total代表当前的累加总和,currentItem是分组里正在遍历的项,每次把当前项的对应字段值加到total里即可。
这个写法和原查询的结果完全一致,只是把Sum换成了手动的累加逻辑~
内容的提问来源于stack exchange,提问作者user6590509
相关产品推荐
相关产品推荐

