Title: Use LINQ Min, Max, and Average extension methods in C#
This example shows how to use LINQ Min, Max, and Average extension methods to get the minimum, maximum, and average values from an array. In order to support LINQ, Microsoft added those extension methods and others. LINQ includes several useful extension methods that apply to arrays, lists, and other collection objects. You can use some of them indirectly in LINQ statements, but you can use them all directly to find things such as minimum, maximum, and average values.
This example uses the following code to demonstrate 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 extension methods to get
// the minimum, maximum, and average values.
txtMin.Text = values.Min().ToString();
txtMax.Text = values.Max().ToString();
txtAve.Text = values.Average().ToString();
}
This code uses a Random object to fill an array with 50 random integers. It then calls the extension methods and displays their results.
Download the example to experiment with it and to see additional details.
|