Use LINQ Min, Max, and Average extension methods in C#

LINQ Min, Max, and Average extension methods

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 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();
}

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in extension methods, LINQ, mathematics and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *