Average

Average can be used to find the average of any numerical collection. It works across a range of types, including complex types with a transform.

Average Elements

Average can be used on any list of a numerical type. This includes Float (Single), Double, Int and Decimal.

using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List{ 1, 2, 3, 4 };
Console.WriteLine(myList.Average()); //Writes 2.5

Average Nullable Collections

Average can be used across the nullable variants of numeric types (For example a nullable integer). When use in this way, null items are ignored and do not affect the output (e.g. They are not counted as 0).

using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List{ 1, 2, null, 3, 4 , null};
Console.WriteLine(myList.Average()); //Writes 2.5

Average Complex Collections With Select Transform

Average can be used across complex objects by passing in a select function to pick the correct numerical value. In our example below, we have a complex type of Person, but in our average function we specify we are averaging the age.

This is more or less short hand for using the LINQ expression select before using Average.

using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List
{
new Person { Age = 1 },
new Person { Age = 2 },
new Person { Age = 3 },
new Person { Age = 4 }
};

Console.WriteLine(myList.Average(x => x.Age)); //Writes 2.5
Console.Write(myList.Select(x => x.Age).Average());//Outputs the same

class Person
{
public int Age { get; set; }
}