System.Linq.Max

Summary

Computes the maximum value of a sequence of values.

public static TSource Max<TSource>(this IEnumerable<TSource> source)
public static TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)

Remarks

This method is implemented by using deferred execution. The immediate return value is an object that stores all the data that is needed to perform the action. The query that is represented by this method is not executed until the object is enumerated, either by calling its GetEnumerator method directly or by using a for each loop in Visual Basic or C#.

The Max method iterates through the elements in the specified sequence and yields the largest value.

If the source sequence is empty, an exception is thrown.

Examples

Example 1: Finding the maximum value in a list of integers

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> numbers = new List<int> { 5, 1, 8, 3, 9, 2 }; int maxNumber = numbers.Max(); Console.WriteLine($"The maximum number is: {maxNumber}"); // Output: The maximum number is: 9 } }

Example 2: Finding the maximum length of strings in a list

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<string> words = new List<string> { "apple", "banana", "kiwi", "strawberry" }; int maxLength = words.Max(word => word.Length); Console.WriteLine($"The maximum string length is: {maxLength}"); // Output: The maximum string length is: 10 } }

Exceptions

  • System.ArgumentNullException: source is null.
  • System.InvalidOperationException: source contains no elements.