In this article, I am going to discuss the Linq Average Method in C# with examples.
Average extension method calculates the average of the numeric items in the collection. Average method returns nullable or non-nullable decimal, double or float value.
The following example demonstrate Agerage method that returns average value of all the integers in the collection.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 }; //Using Method Syntax var MSAverageValue = intNumbers.Average(); //Using Query Syntax var QSAverageValue = (from num in intNumbers select num).Average(); Console.WriteLine("Average Value = " + MSAverageValue); Console.ReadKey(); } } } |
Output:
Average Value = 55
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
IList<Student> studentList = new List<Student>>() { new Student() { StudentID = 1, StudentName = "John", Age = 13} , new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} , new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } }; var avgAge = studentList.Average(s => s.Age); Console.WriteLine("Average Age of Student: {0}", avgAge); |
Output:
Average Age of Student: 17.4