Getting the Average of an Array of Numbers


If you have an array containing a collection of numeric values, you can get the average (mean) using the Averagemethod.
1
2
3
int[] scores = { 89, 98, 72, 100, 83 };
 
double avg = scores.Average();      // 88.4
The Average method is an extension method, applied to Array by virtue of its implementation of the IEnumerableinterface.  It’s part of the System.Linq namespace, so you’ll need a using statement for this namespace.  Average is available in .NET 4 and 3.5.
Average will work for arrays containing any numeric type.