Linq By Example

Max

Max can be used to return the max value in a list. While it’s utility is great on lists of numeric types, it is somewhat limited when running against complex types (Such as custom classes). Instead, a developer should consider using the LINQ statement MaxBy if the return type should be the complex object, rather than the maximum value (See examples below).

Max Elements

Max can be used across any list of numeric elements. This includes Float (Single), Double, Int and Decimal.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List{ 1, 2, 3, 4 };
Console.WriteLine(myList.Max()); //Writes 4

  

Complex Objects Max

Max can be used across complex objects, but the max value is returned rather than the complex object. If the entire complex object is required, see MaxBy.

The complex object must implement IComparable, or a selector function may be passed in (as demonstrated below).
    
using System;
using System.Collections.Generic;
using System.Linq;

List people = new List
{
    new Person
    {
        Name = "John Smith", 
        Age = 20
    }, 
    new Person
    {
        Name = "Jane Smith", 
        Age = 30
    }
};

Console.Write(people.Max(x => x.Age)); //Outputs 30 NOT Jane Smith

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}