C# Min Method

Maximum and minimum values

You want to find the minimum value in a collection (such as an array or List) in a simple way using the C# programming language. With the Min method we can find the minimum element or the minimum value after a transformation.

This C# article shows the Min method from the System.Linq namespace.

Example

Note

First, this program requires the System.Linq namespace. It instantiates an array of integers upon execution; then, the Min() method is called on the array. Finally, the Min() method is called again, but with a lambda expression that makes all values negative.

Lambda Expression
Program that uses Min method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array1 = { 1, -1, 2, 0 };

	// Find minimum number.
	Console.WriteLine(array1.Min());

	// Find minimum number when all numbers are made negative.
	Console.WriteLine(array1.Min(element => -element));
    }
}

Output

-1
-2

Results. You can see that the first call to Min determines that -1 is the smallest integer. The second call changes the 2 to -2, so that is now the smallest integer. Note that the values in the source array (array1) are not mutated.

Summary

The Min method provides a clear way to find the smallest value in a collection. You can also provide a transformation function, which provides a mechanism for you to insert additional logic if needed. Please see also the Max method.

Max Method LINQ Examples
.NET