C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Tip: The Average method looks like an instance method when called, but it is not. It is an 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", "deves" }; 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.
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.
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.
Null TipsForeach Loop Examples
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.
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.
Review: We saw an example of the Average method. We looked into the assembly where it is defined.