Enumerable.Max is extension method from System.Linq namespace. It returns maximal value of numeric collection.
Max for Numeric Types
Gets maximal number from list of integer numbers.
Gets maximal number from list of decimal numbers.
Calling Max on empty collection throws exception.
Max for Nullable Numeric Types
Gets maximal number from list of nullable integers.
Returns null if the collection contains only null values.
Returns null if the collection is empty.
Max with Selector
This example gets length of the longest string.
Max for Types Implementing IComparable
LINQ method Max can be used also on collection of custom type (not numeric type like int or decimal). The custom type have to implement IComparable interface.
Lets have custom type Money which implements IComparable.
And this is usage of Max method on the Money collection.
Max with Query Syntax
LINQ query expression to get maximal item in the collection.
LINQ query expression to get maximal item which matches specified predicate.
LINQ query expression to get maximal string length using selector.
Max with Group By
This example shows how to get maximal value per group. Lets have players. Each player belongs to a team and have a score. Team best score is maximal score of players in a team.
This is .NET Framework implementation of Enumerable.Max method for collection of numeric type (in this case
IEnumerable<int>). Note that it throws the exception for an empty collection on the last line (
This is .NET Framework implementation of Enumerable.Max method for collection of nullable numeric type (in this case
IEnumerable<int?>). Note that it returns null for an empty collection (
int? value = null;). Also notice that it returns null if all values in the collection are null.
- MSDN Enumerable.Max - .NET Framework documentation
- LINQ Aggregation Methods
- LINQ Sum - gets sum of numeric collection
- LINQ Max - gets maximal item from collection
- LINQ Min - gets minimal item from collection
- LINQ Count - counts number of items in a collection (result type is Int32)
- LINQ LongCount - counts number of items in a collection (result type is Int64)
- LINQ Average - computes average value of numeric collection
- LINQ Aggregate - applies aggregate function to a collection