Thursday, May 19, 2011

C# Aggregate Method

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. Here, we provide some simple examples of Aggregate.

Examples

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.

 

Program 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