Aggregate. This C# method applies a method to each element. It applies a function to each successive element. We specify the function with a Func (often with lambda syntax).
With this extension method, we act upon the aggregate of all previous elements. This makes certain methods, such as sum, possible.
Add example. The first call uses a Func that specifies that the accumulation should be added to the next element. This results in the sum of all the elements in the array.
Info With Aggregate we "accumulate" values, meaning we build up values from each previous function call.
using System;
using System.Linq;
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);15
Multiply example. The second call is more interesting. It multiplies the accumulation with the next element. The difference between adding and multiplying is significant.
using System;
using System.Linq;
int[] array = { 1, 2, 3, 4, 5 };
int result = array.Aggregate((a, b) => b * a);
// 1 * 2 = 2// 2 * 3 = 6// 6 * 4 = 24// 24 * 5 = 120
Console.WriteLine(result);120
Func. The Aggregate method receives a higher-order procedure of type Func. The Func receives 2 arguments and returns a third. This is the accumulator function.
Extensions. Aggregate() is the first method listed in Visual Studio on many collections (like arrays). Visual Studio is presenting extension methods.
So The list of methods, starting with Aggregate, are methods from a namespace called System.Linq.
Summary. Aggregate is a declarative way of applying an accumulator function to a collection of elements. It can multiply or add all elements together.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.