[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.