LINQ Average Method Example

Average method is used when we want to find the average value of any numerical list, like average score, average income etc.

Here we see how to use Average method in LINQ query with complex object list!

Average is extension method comes under System.Linq namespace, It calculates average value of any list of numbers.

Average method LINQ C#

Let's look at some example, First, we create a list of student objects, where each student has some different score.

var studentsStream = new List<Student> {
    new Student { FullName = "Aruna WTR", StreamId=1,  Score = 10 },
    new Student { FullName = "Janet WTR", StreamId=2,  Score = 9  },
    new Student { FullName = "Ajay WTR", StreamId=1,  Score = 11 },
    new Student { FullName = "Kunal WTR", StreamId=2,  Score = 13  },
    new Student { FullName = "Chandra WTR", StreamId=2,  Score = 8  },
};

We will calculate the average score of all students from above student list.

LINQ query expression to calculate average

We also can use query expression to find the average value of products.

var result = (from s in studentsStream select s.Score).Average();
Console.WriteLine(result);
LINQ Average with GroupBy

We will calculate the average score of each Stream from above student list. calculate average with GroupBy

var avgScorebyStream = studentsStream .GroupBy(g => g.StreamId, s => s.Score) .Select(g => new
    { 
        StreamId = g.Key, 
        AvgScore = g.Average() 
    });


foreach (var s in avgScorebyStream) 
{ 
    Console.WriteLine(string.Format("{0}-{1}", s.StreamId,s.AvgScore)); 
}

Remember, average method can work on only numerical field.

 
LINQ Average Method
LINQ (language integrated query) allow you to write query on database objects like ado.net, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join Asp.net MVC Course