Average is a LINQ functionality which calculates average value of given collection. It works with both collections of primitive values and complex objects. Below article provides example of each one.
List of integers
1 |
var items = new List<int>() { 1, 2, 3, 4, 5 }; |
Average value can be calculated by calling Average function.
1 |
var avg = items.Average(); // avg = 3 |
In case of collection having null values, such items are being ignored when calculating average. As it is presented on below example, there are two additional null elements, but result is still 3.
1 2 3 |
var items = new List<int?>() { null, 1, 2, 3, 4, 5, null }; var avg = items.Average(); // avg = 3 |
List of objects
It is possible to calculate average value of selected property of given objects collection. For such purpose let’s use example Fruit class. It contains Price property, which we’ll use to get average figure.
1 2 3 4 5 |
public class Fruit { public string Name { get; set; } public decimal Price { get; set; } } |
We also need some sample list of Fruit objects.
1 2 3 4 5 6 7 8 |
var fruits = new List<Fruit>() { new Fruit() { Name = "Orange", Price = 4.5M }, new Fruit() { Name = "Pear", Price = 2.9M }, new Fruit() { Name = "Apple", Price = 1.8M }, new Fruit() { Name = "Lemon", Price = 2.1M }, new Fruit() { Name = "Banana", Price = 2.7M } }; |
Finally, we can call Average to get the result. This time it requires an argument which is a selector of an object against which average will be calculated. In our case it is Price property.
1 |
var avg = fruits.Average(x => x.Price); // avg = 2.8 |