LINQ stands for Language Integrated Query.You can use the Average method to calculate the average of numerical values in a collection.
It returns a single value which is an average of the values in the collection.
If we execute the following then we get the average as 3.
IList<int> list = new List<int>() {1,2,3,4,5};
var avg= list.Average();
Console.WriteLine(avg);
Other than int average can be used with double,float or decimal values also.Following Average function call returns the value 3.2
IList<float> list = new List<float>() {1.5f,2f,3f,4.5f,5f};
var avg= list.Average();
Console.WriteLine(avg);
Calculating average of specific items in a collection using Average function
In the following example we are calculating average of list items after filtering the items.
We have declared student class as:
class Student
{
public string Name { get; set; }
public string Subject { get; set; }
public int Marks { get; set; }
}
We can calculate the marks of a particular student by using the following
IList<Student> list = new List<Student>() {
new Student{Name="Mark",Subject="Maths",Marks=60},
new Student{Name="John",Subject="English",Marks=66},
new Student{Name="Mark",Subject="English",Marks=76},
new Student{Name="Ajay",Subject="Maths",Marks=66}
};
var avg= list.Where(x=>x.Name=="Mark").Select(x=>x.Marks).Average();
Console.WriteLine(avg);
Leave a Reply