C# Max Method

Maximum and minimum values

How can we find the maximum value in a collection? The Max method looks through the source collection and returns the largest value. It can be used both with the default values in the collection and also with a transformation function.

Example

To begin, this program instantiates an array of four integers on the heap: it contains the values -2 through 1. Next, the Max method is called upon this array. Finally, we use another version of Max that receives a lambda expression; this translates all the values into their absolute values before comparing them.

Lambda Expression

This C# example program demonstrates the Max method from System.Linq.

Program that uses Max method [C#]

using System;
using System.Linq;

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

	// Find maximum number.
	Console.WriteLine(array1.Max());

	// Find maximum number when all numbers are made positive.
	Console.WriteLine(array1.Max(element => Math.Abs(element)));
    }
}

Output

1
2
Note

Results. You can see that the Max method returns 1 when called with no parameters; this is because 1 is the largest value in the array. When the Math.Abs transformation is used, though, the value 2 is returned because the absolute value of -2 is 2, and this is larger than 1. Notice that the original value is not returned—the transformed value is.

Math.Abs: Absolute Value

Summary

The Max function can find either the maximum value in a collection, or the maximum value after a specific transformation is applied, such as an absolute value. Max is precisely opposite the Min function, which is also detailed on this site.

Min Method LINQ Examples
.NET