Convert Amount to Aggregated 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 g.SumI would like to get a math product using Aggregate.

To make sure that it works the same way .Sum(but as a product), I tried to make an Aggregate function that just returns the amount ...

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

However, this does not give the same result as when used .Sum. Any ideas why?

nextItem.Scorehas type double?.

+3
source share
3 answers
public static class MyExtensions
{
    public static double Product(this IEnumerable<double?> enumerable)
    {
        return enumerable
          .Aggregate(1.0, (accumulator, current) => accumulator * current.Value);
    }
}
+3
source

The fact is that in your example you start multiplication with 0.0 - multiplication with a zero value equal to zero, at the end the result will be zero.

. , true 1. , , 1.0.

+1

( ), .

Aggregate, - http://msdn.microsoft.com/en-us/library/bb549218.aspx

int product = sequence.Aggregate((x, acc) => x * acc);

item1 * (item2 * (item3 * ... * itemN)).

int product = sequence.Aggregate(1.0, (x, acc) => x * acc);

1.0 * (item1 * (item2 * (item3 * ... * itemN))).

//: . - InvalidOperationException, . , 1.0.

0

Source: https://habr.com/ru/post/1787283/


All Articles