C# Examples

Menu:


C# LINQ Aggregation Methods

Average (LINQ)

Enumerable.Average is extension method from System.Linq namespace. It computes average value of numeric collection.

Average Examples

Computes average of int values. The result type is double.

Computes average of decimal values. The result type is decimal.

Computes average of nullable int values. The result type is nullable double. The null values in collection are ignored for calculation.

If Average method is called on empty collection, it throws the exception.

If Average method is called on empty collection of nullable type, it returns null.

Average with Selector

You can calculate average value on collection of any type (IEnumerable<T>), but you have to tranform the type T into any numeric type using selector. It can be done by Select method or using selector as a parameter of the Average method.

This example counts the average length of the strings.

Average with Query Syntax

LINQ query expression to calculate average value of all items in the collection.

LINQ query expression to calculate average value of items which match specified predicate.

LINQ query expression to calculate average string length using selector.

Average with Group By

This example shows how to calculate average value for each group. Lets have players. Each player belongs to a team and have a score. The result is average score per player in a team.

Average Implementation

This is .NET Framework implementation of Enumerable.Average method for collection of numeric types (in this case IEnumerable<int>). Note that it throws the exception for an empty collection on the last line (throw Error.NoElements();)).

This is .NET Framework implementation of Enumerable.Average method for collection of nullable numeric types (in this case IEnumerable<int?>). Note that it returns null for an empty collection on the last line (return null;). Also notice that it ignores null values (if (v != null) {)


See also

  • C# List - illustrative examples of all List<T> methods
  • C# foreach - how foreach and IEnumerable works debuggable online
By Jan Slama, 24-Mar-2016