Aggregation operations computes a single value from a collection of values.
Aggregate
Performs a custom aggregation operation on the values of a collection.
Method Syntax
// Aggregate
var numbers = new int[] { 1, 2, 3, 4, 5 };
var product = numbers.Aggregate(1, (acc, n) => acc * n);
// product = 120
Query Syntax
// Not applicable.
Average
Calculates the average value of a collection of values.
Method Syntax
// Average
var numbers = new int[] { 1, 2, 3, 4, 5 };
var average = numbers.Average();
// average = 3
Query Syntax
// Not applicable.
Count
Counts the elements in a collection, optionally only those elements that satisfy a predicate function.
Method Syntax
// Count
var numbers = new int[] { 1, 2, 3, 4, 5 };
int count = numbers.Count(n => n % 2 == 0);
// count = 2
Query Syntax
// Not applicable.
LongCount
Counts the elements in a large collection, optionally only those elements that satisfy a predicate function.
Method Syntax
// LongCount
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
long count = numbers.LongCount();
// count = 10
Query Syntax
// Not applicable.
Max
Determines the maximum value in a collection. Throws exception if collection is empty.
Method Syntax
// Max
var numbers = new int[] { 1, 2, 3, 4, 5 };
var max = numbers.Max();
// max = 5
Query Syntax
// Not applicable.
Min
Determines the minimum value in a collection. Throws exception if collection is empty.
Method Syntax
// Min
var numbers = new int[] { 1, 2, 3, 4, 5 };
var min = numbers.Min();
// min = 1
Query Syntax
// Not applicable.
Min-/MaxOrDefault
Unlike other LinQ extensions
Min()
andMax()
do not have an overload without exceptions. Therefor theIEnumerable
must be checked forAny()
before callingMin()
orMax()
// Max
var numbers = new int[] { };
var max = numbers.Any() ? numbers.Max() : 0;
// max = 0
Sum
Calculates the sum of the values in a collection.
Method Syntax
// Sum
var numbers = new int[] { 1, 2, 3, 4, 5 };
var sum = numbers.Sum();
// sum = 15
Query Syntax
// Not applicable.