
Aggregate applies a method to each element. You want to apply a function to each successive element in your C# collection. With the Aggregate extension method, you can apply each successive element to the aggregate of all previous elements.
This C# example program uses the Aggregate extension method from System.Linq.

There are two example calls to the Aggregate method here. The first call uses a Func that specifies that the accumulation should be added to the next element. This simply results in the sum of all the elements in the array. The second call is more interesting: it multiplies the accumulation with the next element. All the numbers are multiplied together in order.
SumProgram that calls Aggregate method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5 };
int result = array.Aggregate((a, b) => b + a);
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15
Console.WriteLine(result);
result = array.Aggregate((a, b) => b * a);
// 1 * 2 = 2
// 2 * 3 = 6
// 6 * 4 = 24
// 24 * 5 = 120
Console.WriteLine(result);
}
}
Output
15
120
The Aggregate method receives a higher-order procedure of type Func. The Func receives two arguments and returns a third. This is the accumulator function. You can read more about the Func type itself here.
Func
The Aggregate method is a declarative way of applying an accumulator function to a collection of elements. This means you can multiply or add all elements together. More complicated accumulator functions can also be used, and would be likely required in certain applications for Aggregate to be beneficial.
System.Linq