c# - 将 Sum 转换为聚合乘积表达式

标签 c# linq aggregate aggregate-functions

我有这样的表达:

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.Scoredouble? 类型。

最佳答案

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/

相关文章:

c# - 能否使用 Azure 数据工厂在 Azure Blob 中生成 CSV

c# - 使用 SSH 连接 Unix/Solaris 和 .NET

c# - 平滑曲线的算法

带有子查询/分组依据/加入的 LINQ

c# - 存储库与 OrderBy

MySQL 条件 select else 聚合语句

python - Pandas 聚合计数不同

c# - 如何使用其列和行索引值设置数据网格单元格的值?

c# - 根据大小对数字范围进行分区,然后找到该范围内给定数字的分区起点

r - 将 15 分钟的数据汇总到每小时