14,599,597 members
Rate this:
See more:

int[] numbers = { 1, 4, 7, 10 };
int product = numbers.Aggregate(1, (interim, next) => interim * next);
Console.WriteLine(product); // output: 280

What I have tried:

`I am unable to understand how this code works`
Posted
Updated 9-Dec-19 11:01am

Rate this:

## Solution 2

It's a Linq Method - Aggregate - which takes two parameters: a starting value - `1`, and a lambda expression - `(interim, next) => interim * next` which explains what to return.
The lambda comes in two parts, separated by "`=>`":
1) The first part names the parameters as `interim` (the result so far) and `next` (the value for this element.
2) The second part is is the expression which generates the total for each element as it loops through them.

Think of it as a "raw" loop:
```int product = 1;
foreach (int next in numbers)
{
product = product * next;
}
Console.WriteLine(product);
```
Rate this:

## Solution 3

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); // output: 560```

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.

Rate this:

## Solution 1

This code is using the aggregate function[^] to return the product of elements of specified array.