Average

In LINQ, we sometimes need to calculate the Average value of any numeric item present in the collection. To execute this operation, we can use the Average operator. Let's go through the following code example to see how it works. Let's assume we have the following class:

 public class Student
{
public int rollNum { get; set; }
public string Name { get; set; }
public string classID { get; set; }
public int age { get; set; }
}

Now, we have created the following objects for the student class:

List<Student> students = new List<Student>();
students.Add(new Student { rollNum = 1, classID = "1", Name = "Sia Bhalla", age = 1 });
students.Add(new Student { rollNum = 2, classID = "2", Name = "James Donohoe", age = 35 });
students.Add(new Student { rollNum = 3, classID = "1", Name = "Myra Thareja", age = 8 });

To calculate the average age of the students, we can use the following code statement:

var avg = students.Average(s => s.age); 

If we execute the code, we get the following output:

In the next section, we will look at the GroupBy operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155