Calculate average of values in a List in C#
This post will discuss how to calculate the average of values in a List in C#.
The Enumerable.Average method is the shortest and most idiomatic way to compute the average of a sequence of numeric values. The following code example shows invocation for this method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> numbers = new List<int> { 1, 4, 6, 8 }; double average = numbers.Average(); Console.WriteLine("The average is {0}", average); } } |
Output:
The average is 4.75
The Enumerable.Average method throws System.InvalidOperationException if the source sequence is empty. You can easily handle the exception as follows.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> numbers = new List<int> { 1, 4, 6, 8 }; double average = numbers.Count > 0 ? numbers.Average() : 0.0; Console.WriteLine("The average is {0}", average); } } |
Output:
The average is 4.75
The Enumerable.Average method has an overload that takes a transform function to apply to each element. It can be used to compute an average of some specific field from a list of objects, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Linq; using System.Collections.Generic; public class Person { public string name { get; set; } public int age { get; set; } public Person(string name, int age) { this.name = name; this.age = age; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { List<Person> persons = new List<Person> { new Person("x", 27), new Person("y", 20), new Person("z", 24), new Person("z", 30) }; double average = persons.Count > 0 ? persons.Average(item => item.age) : 0.0; Console.WriteLine("The average is {0}", average); } } |
Output:
The average is 25.25
The transform function can also be invoked on each element of the input sequence of String values to compute the average.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> numbers = new List<string> { "1", "4", "6", "8" }; double average = numbers.Average(num => int.Parse(num)); Console.WriteLine("The average is {0}", average); } } |
Output:
The average is 4.75
That’s all about calculating the average of values in a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)