Use LINQ's Min, Max, and Average extension methods to get the minimum, maximum, and average values in an array in C#

In order to support LINQ, Microsoft added extension methods to Visual Studio. These let you add new features to existing classes. LINQ includes several useful extension methods that apply to arrays, lists, and other collection objects. You can use them directly to find things such as minimum, maximum, and average values.

The following code demonstrates the Min, Max, and Average LINQ extension methods.

// Make some random values.
private void Form1_Load(object sender, EventArgs e)
{
const int num_values = 50;
Random rand = new Random();
int[] values = new int[num_values];
for (int i = 0; i < num_values; i++)
{
values[i] = rand.Next(0, 10000);
}

// Display the values.
lstValues.DataSource = values;

// Use LINQ extention methods to get
// the minimum, maximum, and average values.
txtMin.Text = values.Min().ToString();
txtMax.Text = values.Max().ToString();
txtAve.Text = values.Average().ToString();
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.