我有这样的表达:
group i by i.ItemId into g
select new
{
Id = g.Key,
Score = g.Sum(i => i.Score)
}).ToDictionary(o => o.Id, o => o.Score);
而不是 g.Sum
我想使用 Aggregate
获得数学乘积。
为了确保它与 .Sum
一样工作(但作为产品),我尝试制作一个聚合函数,它只返回总和...
Score = g.Aggregate(0.0, (sum, nextItem) => sum + nextItem.Score.Value)
但是,这不会给出与使用 .Sum
相同的结果。任何 idas 为什么?
nextItem.Score
是 double?
类型。
最佳答案
public static class MyExtensions
{
public static double Product(this IEnumerable<double?> enumerable)
{
return enumerable
.Aggregate(1.0, (accumulator, current) => accumulator * current.Value);
}
}
关于c# - 将 Sum 转换为聚合乘积表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774062/