This post will discuss how to calculate the average of values in a List in C#.

The Enumerable.Average method is the shortest and most idiomatic way to compute the average of a sequence of numeric values. The following code example shows invocation for this method:

Download  Run Code

Output:

The average is 4.75

 
The Enumerable.Average method throws System.InvalidOperationException if the source sequence is empty. You can easily handle the exception as follows.

Download  Run Code

Output:

The average is 4.75

 
The Enumerable.Average method has an overload that takes a transform function to apply to each element. It can be used to compute an average of some specific field from a list of objects, as demonstrated below:

Download  Run Code

Output:

The average is 25.25

 
The transform function can also be invoked on each element of the input sequence of String values to compute the average.

Download  Run Code

Output:

The average is 4.75

That’s all about calculating the average of values in a List in C#.