C# LINQ Aggregation Methods
Following examples show how to use LINQ aggregation methods defined in Enumerable class.
Returns sum of values in numeric collection.
int result = numbers.Sum();
Returns zero for empty collection.
int result = numbers.Sum();
Returns maximal value in numeric collection.
int result = numbers.Max();
Throws InvalidOperationException for empty collection.
int result = numbers.Max();
Returns minimal value in numeric collection.
int result = numbers.Min();
Throws InvalidOperationException for empty collection.
int result = numbers.Min();
Returns number of items in a collection.
int result = items.Count();
Returns zero for empty collection.
int result = items.Count();
Returns number of items in a collection. The result is of type long (Int64), so the number of items can be greater than Int32.MaxValue (2,147,483,647).
long result = items.LongCount();
Returns zero for empty collection.
long result = items.LongCount();
Returns average value of numeric collection.
double result = numbers.Average();
Throws InvalidOperationException for empty collection.
double result = numbers.Average();
Aggregate method applies a function to each item of a collection. In this example the function to be applied is adding (operator +).
int sum = numbers.Aggregate( func: (result,item) => result+item );
Throws InvalidOperationException for empty collection.
int sum = numbers.Aggregate( func: (result,item) => result+item );
See also
- C# Foreach - how foreach and IEnumerable works debuggable online