C# Average Extension (Get Average of All Values)

This C# example program uses the Average extension method. It requires System.Linq.
Average is an extension method. It computes the average value using only one statement. It provides a declarative way to compute the average value of a sequence in the C# language.
Example. First, programs that use the Average method require the "using System.Linq" directive to include the LINQ namespace. The Average method implementation is actually stored in the System.Core.dll file.LINQ

Tip: The Average method looks like an instance method when called, but it is not. It is an extension method.


Here: We get the average of all the values in the double array by calling the Average extension method.

C# program that computes averages using System; using System.Linq; class Program { static void Main() { // // Use Average to compute average value. // double[] array1 = { 1, 2, 3, 5, 0 }; double average1 = array1.Average(); Console.WriteLine(average1); // // Use Average to compute average string length. // string[] array2 = { "dog", "cat", "perls" }; double average2 = array2.Average(x => x.Length); Console.WriteLine(average2); } } Output 2.2 3.66666666666667
There is one overload that accepts no parameters. There are more overloads that allow you to "select" the values you want to average from another collection with a selector delegate, which you can provide as a lambda expression.Lambda

Review: The first part of the program shows how to directly average the values in a double[] collection.

Note: Average is equivalent to adding up the total of all of the numbers, and then dividing that total by the number of elements.

Next, we use the Average method parameter to specify a function that will select a value from an existing sequence. The lambda expression "x => x.Length" extracts the length of the strings and then averages those values.String Length
Internals. If you provide a selector parameter to Average, the method internally calls the Select extension method first. On that result, it then checks the parameter for null, uses a foreach-loop, and divides the total value by the count.NullForeach
Also, it will throw an exception if it divides by zero. Because of all the overhead in this method, this implementation will be slower than directly accessing array elements and computing the average in a for-loop.For
Summary. You can use Average to compute the average value of a collection of numbers. And you can combine the Average extension with a Func selector. This Func will internally Select the elements you specify in the lambda expression.Func
Dot Net Perls