Aggregate (LINQ)

Enumerable.Aggregate is C# version of fold or reduce function. It is extension method from System.Linq namespace.

Aggregate method applies a function to each item of a collection. For example, let's have collection { 6, 2, 8, 3 } and the function Add (operator +) it does (((6+2)+8)+3) and returns 19.

Aggregate alternative for Sum

Implementation of Sum using Aggregate method. This example use Aggregate method overload with only one parameter func. Into the func parameter there is passed lambda expression (anonymous method) which adds two numbers.

This example is for demonstration purpose only. To compute sum of numbers use rather Enumerable.Sum.

In this example there is passed named method Add insted of lambda expression.


Aggregate alternative for Average

Implementation of Average using Aggregate method. There is used Aggregate method overload with three parameters, seed, func and resultSelector.

This example is for demonstration purpose only. To compute average value use rather Enumerable.Average.

Aggregate Implementation

This is .NET Framework implementation of Enumerable.Aggregate method with only one paramater func.

This is .NET Framework implementation of Enumerable.Aggregate method with three parameters seed, func and resultSelector.


See also

By Jan Slama, 28-Apr-2016
;