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
- MSDN Enumerable.Aggregate - .NET Framework documentation
- Fold function - fold / reduce / aggregate function on Wikipedia
- Fun with Linq Aggregate - Parse CSV using LINQ Aggregate
- LINQ Aggregate algorithm explained - StackOverflow
- LINQ Aggregation Methods
- LINQ Sum - gets sum of numeric collection
- LINQ Max - gets maximal item from collection
- LINQ Min - gets minimal item from collection
- LINQ Count - counts number of items in a collection (result type is Int32)
- LINQ LongCount - counts number of items in a collection (result type is Int64)
- LINQ Average - computes average value of numeric collection
- LINQ Aggregate - applies aggregate function to a collection
- C# List - illustrative examples of all List<T> methods
- C# foreach - how foreach and IEnumerable works debuggable online