Home
C#
Average Method
This page was last reviewed on Nov 29, 2023.
Dot Net Perls
Average. This is a C# extension method. It computes the average value using only one statement. Often we combine it with other LINQ methods.
LINQ
Shows an array
Average notes. This method provides a declarative way to compute the average value of a sequence in the C# language. We can use Average with no argument, or pass in a lambda expression.
Lambda
Example. First, add the "using System.Linq" directive to include the LINQ namespace. The Average method implementation is 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.
Extension
Info The program shows how to directly average the values in a double array 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.
Divide
Shows an array
using System; using System.Linq; // Use Average to compute average value. double[] array = { 1, 2, 3, 5, 0 }; double average = array.Average(); Console.WriteLine("AVERAGE: {0}", average);
AVERAGE: 2.2
Overload, lambda. There are more overloads to Average. We can select the values we want to average from another collection with a selector delegate. We can pass a lambda expression.
Here We use the Average method parameter to specify a function that will select a value from an existing sequence.
Tip The lambda expression extracts the length of the strings and then averages those values.
String Length
using System; using System.Linq; // Use Average to compute average string length. string[] array = { "dog", "cat", "perls" }; double average = array.Average(x => x.Length); Console.WriteLine("AVERAGE: {0}", average);
AVERAGE: 3.66666666666667
Internals. How does Average() work? If you provide a selector parameter to Average, the method internally calls the Select extension method first.
Then On that result, Average() checks the parameter for null, uses a foreach-loop, and divides the total value by the count.
null
foreach
Also The Average extension method will throw an exception if it divides by zero.
Warning Because of all the overhead in this method, this implementation will be slower than a for-loop approach.
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 will internally Select elements.
Func
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 29, 2023 (edit link).
Home
Changes
© 2007-2024 Sam Allen.