DEV Community

Andre Carstens
Andre Carstens

Posted on • Updated on

C# arrays using Average

Average is used to get the average of all values within an array.
For example, you can get the average value of all the items in the integer array by using average

int[] nums = new int[] { 1, 4, 5, 2, 3, 5, 6 };

//normal array average
var average = nums.Average();

Enter fullscreen mode Exit fullscreen mode

This will return a double with the value of: 3.7142857142857144

Question:

Can you use a select to filter the items used in average of an array?
Lets try

var averageSelected = nums.Where(x => x >= 2).Select(x => x).Average();

Enter fullscreen mode Exit fullscreen mode

In the code above, the integer array nums is first trimmed using the .Where clause, the .Select clause will choose the value of the array and the .Average() will return the average of the selected values that matched the .Where statement.

Top comments (0)