C# Examples

Menu:


C# LINQ Aggregation Methods

C# LINQ Aggregation Methods

Following examples show how to use LINQ aggregation methods defined in Enumerable class.

Enumerable.Sum

Returns sum of values in numeric collection.

numbers:8 2 6 3
int result = numbers.Sum();
result:19

Returns zero for empty collection.

numbers:(empty)
int result = numbers.Sum();
result:0

Enumerable.Max

Returns maximal value in numeric collection.

numbers:8 2 6 3
int result = numbers.Max();
result:8

Throws InvalidOperationException for empty collection.

numbers:(empty)
int result = numbers.Max();
(exception)

Enumerable.Min

Returns minimal value in numeric collection.

numbers:8 2 6 3
int result = numbers.Min();
result:2

Throws InvalidOperationException for empty collection.

numbers:(empty)
int result = numbers.Min();
(exception)

Enumerable.Count

Returns number of items in a collection.

items:A B C D
int result = items.Count();
result:4

Returns zero for empty collection.

items:(empty)
int result = items.Count();
result:0

Enumerable.LongCount

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).

items:A B C D
long result = items.LongCount();
result:4

Returns zero for empty collection.

items:(empty)
long result = items.LongCount();
result:0

Enumerable.Average

Returns average value of numeric collection.

numbers:8 2 6 3
double result = numbers.Average();
result:4.75

Throws InvalidOperationException for empty collection.

numbers:(empty)
double result = numbers.Average();
(exception)

Enumerable.Aggregate

Aggregate method applies a function to each item of a collection. In this example the function to be applied is adding (operator +).

numbers:8 2 6 3
int sum = numbers.Aggregate( func: (result,item) => result+item );
sum:19

Throws InvalidOperationException for empty collection.

numbers:(empty)
int sum = numbers.Aggregate( func: (result,item) => result+item );
(exception)

See also

  • C# Foreach - how foreach and IEnumerable works debuggable online
By Jan Slama, 15-May-2016