How to Use LINQ Max and Min in C# - Simple Guide
In C#, use
Max() and Min() methods from LINQ to find the largest and smallest values in a collection. These methods work on arrays, lists, or any enumerable data and return the maximum or minimum element respectively.Syntax
The Max() and Min() methods are called on a collection to find the highest or lowest value. You can use them directly on numeric collections or with a selector function for complex types.
- Max:
collection.Max()orcollection.Max(x => x.Property) - Min:
collection.Min()orcollection.Min(x => x.Property)
These methods return the maximum or minimum value found.
csharp
var maxValue = collection.Max(); var minValue = collection.Min(); // With selector var maxProperty = collection.Max(x => x.Property); var minProperty = collection.Min(x => x.Property);
Example
This example shows how to find the maximum and minimum numbers in a list using LINQ's Max() and Min() methods.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 5, 3, 9, 1, 7 }; int maxNumber = numbers.Max(); int minNumber = numbers.Min(); Console.WriteLine($"Max number: {maxNumber}"); Console.WriteLine($"Min number: {minNumber}"); } }
Output
Max number: 9
Min number: 1
Common Pitfalls
Common mistakes when using Max() and Min() include:
- Calling these methods on an empty collection causes an
InvalidOperationException. - Using them on collections with
nullvalues without handling can cause errors. - For complex objects, forgetting to provide a selector function to specify which property to compare.
Always check if the collection has elements before calling Max() or Min().
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> emptyList = new List<int>(); // Wrong: throws exception // int max = emptyList.Max(); // Right: check before calling if (emptyList.Any()) { int max = emptyList.Max(); Console.WriteLine(max); } else { Console.WriteLine("List is empty."); } } }
Output
List is empty.
Quick Reference
| Method | Description | Example |
|---|---|---|
| Max() | Returns the largest value in a collection | numbers.Max() |
| Min() | Returns the smallest value in a collection | numbers.Min() |
| Max(selector) | Returns the largest value based on a property | people.Max(p => p.Age) |
| Min(selector) | Returns the smallest value based on a property | people.Min(p => p.Age) |
Key Takeaways
Use LINQ's Max() and Min() to find highest and lowest values in collections easily.
Always check if the collection is not empty before calling Max() or Min() to avoid exceptions.
For complex objects, provide a selector function to specify which property to compare.
Max() and Min() work on any IEnumerable including arrays and lists.
Handle null values carefully to prevent runtime errors.