Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Sum to an Aggregate product expression

I have this expression:

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);

and instead of g.Sum I'd like to get the mathematical product using Aggregate.

To make sure it worked the same as .Sum (but as product) I tried make an Aggregate function that would just return the sum...

Score = g.Aggregate(0.0, (sum, nextItem) => sum + nextItem.Score.Value)

However, this does not give the same result as using .Sum. Any idas why?

nextItem.Score is of type double?.

like image 617
Mickel Avatar asked Sep 16 '25 22:09

Mickel


2 Answers

public static class MyExtensions
{
    public static double Product(this IEnumerable<double?> enumerable)
    {
        return enumerable
          .Aggregate(1.0, (accumulator, current) => accumulator * current.Value);
    }
}
like image 83
Ohad Schneider Avatar answered Sep 19 '25 12:09

Ohad Schneider


The thing is that in your example you are starting the multiplication with 0.0 - A multiplication with zero yields zero, at the end the result will be zero.

Correct is to use the identity property of multiplication. While adding zero to a number leaves the number of unchanged, the same property holds true for a multiplication with 1. Hence, the correct way to start a product aggregate is to kick off multiplication wit the number 1.0.

like image 20
flq Avatar answered Sep 19 '25 10:09

flq