C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The Average method looks like an instance method when called, but it is not. It is an extension method.
ExtensionInfo: 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.
C# program that computes averages
using System;
using System.Linq;
class Program
{
static void Main()
{
// Use Average to compute average value.
double[] array = { 1, 2, 3, 5, 0 };
double average = array.Average();
Console.WriteLine("AVERAGE: {0}", average);
}
}
Output
AVERAGE: 2.2
Here: We use the Average method parameter to specify a function that will select a value from an existing sequence.
Tip: The lambda expression "x => x.Length" extracts the length of the strings and then averages those values.
String LengthC# program that uses Average with lambda
using System;
using System.Linq;
class Program
{
static void Main()
{
// Use Average to compute average string length.
string[] array = { "dog", "cat", "Codex" };
double average = array.Average(x => x.Length);
Console.WriteLine("AVERAGE: {0}", average);
}
}
Output
AVERAGE: 3.66666666666667
Then: On that result, Average() checks the parameter for null, uses a foreach-loop, and divides the total value by the count.
NullForeachAlso: 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