How to Find the Average Value of a List Using LINQ Average

Often times when dealing with large lists of numbers (or strings), we need to find the average value of the list. Maybe we are calculating a student's GPA, or trying find the average age of visitors to a website. In the 2.0 world, we had to create a loop (typically foreach), count all the values in the list, then divide by the number of items in the list. Now, thanks to LINQ, we can call a new extension – Average.

Microsoft Explanation:

Computes the average of a sequence of nullable Int32
values that is obtained by invoking a projection function on each element of the
input sequence.

In layman's terms, it calculates the average of a list of Int32 values, and returns the result as a double.

Using our scenario above, let's calculate the average age of visitors to a website, using the 2.0 method, and the new LINQ Average method.

Calculating Average Age of Visitors Using C# 2.0

// build a list and get the average value of the list
List<int> AgeList = new List<int>() { 25, 25, 26, 32, 27, 22, 42, 50, 23, 18, 51 };

// holds the sum of ages from the list
int AgeCounter = 0;

// loop through the list and get the sum of all ages
foreach (int age in AgeList)
    AgeCounter += age;

// get the average of all ages (Sum / Number of items in list)
double avg = AgeCounter / AgeList.Count;

// output the result
Console.WriteLine(string.Format("Average value of list: {0}", avg));

// Outputs:
// Average value of list: 31

 

Calculating Average Age of Visitors Using LINQ Average

// build a list and get the average value of the list
List<int> AgeList = new List<int>() { 25, 25, 26, 32, 27, 22, 42, 50, 23, 18, 51 };

// get the average age
double avg = AgeList.Average();

// output the results
Console.WriteLine(string.Format("Average value of list: {0}", avg));

// Outputs:
// Average value of list: 31

Another example of using LINQ Average is to find the average length of strings in a List. This example is taken from the Microsoft Documentation.

Calculating Average String Length of a List Using LINQ Average

string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };
double average = fruits.Average(s => s.Length);
Console.WriteLine("The average string length is {0}.", average);
/*
 This code produces the following output:

 The average string length is 6.5.
*/ 

As we can see, LINQ Average allows use to use a Lambda expression also, for a more refined Average calculation.

If have questions, comments, or suggestion, please feel to post them in the LINQ Exchange Forum

GD Star Rating
loading...
GD Star Rating
loading...
How to Find the Average Value of a List Using LINQ Average, 4.1 out of 5 based on 7 ratings
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply