Finding the average value in a sequence with LINQ C#
August 1, 2014 2 Comments
The LINQ Average operator can be applied to sequences of numeric types. In its simplest form it returns an average value of type double:
List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 };
double average = integers.Average();
…which gives about 552.14.
The operator can be applied to sequences of custom objects using a selector function:
public class Singer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int BirthYear { get; set; }
}
IEnumerable<Singer> singers = new List<Singer>()
{
new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
};
double averageBirthYear = singers.Average(s => s.BirthYear);
…which is of course not too meaningful, but you get the idea.
View the list of posts on LINQ here.