DEV Community

Andre Carstens
Andre Carstens

Posted on • Edited 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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️