Here's the definition for the extension method.
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);
As Griff says in his solution, it's equivalent to a
for
loop. It can be confusing, the first parameter is a seed, it does not reference the first item in the array, it's an additional value. So, if it was 2 instead of 1, the result would be 560. I prefer to name the parameters in a similar way to those given in the definition and use 'item' for an item of the enumerable.
int[] numbers = { 1, 4, 7, 10 };
int product = numbers.Aggregate(seed:2,(accumulator, item) => accumulator * item);
Console.WriteLine(product);
You don't actually need to set the seed value in your example. There is an overload of the method that uses the first value of the enumerable as the seed.
int[] numbers = { 1, 4, 7, 10 };
int product = numbers.Aggregate((accumulator, item) => accumulator * item);
An interesting point about the seed is that it can be a different
Type
to the enumerable
Type
but it's of the same
Type
that's returned from the method. There's another overload of the method that lets you use the result of the aggregation as the parameter of a function. So you can do something like this. Define the seed as a
double
and return a
double
from the function.
var intCollection = new int[] { 1,2,3,4 };
double squareRoot10 = intCollection.Aggregate(0.00D,
(accumulator, item) => accumulator += item,
accumulator=> Math.Sqrt(accumulator));
A more practical example would be to construct your own accumulator
Type
with methods to process the 'items' and to return the result of the accumulation.