Linq By Example

MaxBy

MaxBy is able to find maximum values, and then return the entire object from a list rather than the single property. It is important to note that MaxBy is a .NET 6 only feature. You cannot use MaxBy in any version of .NET Core, any version of .NET Framework, or .NET 5. You must be using .NET 6.

MaxBy vs Max

The main difference between MaxBy and Max is that while Max will return only the single maximum property value, MaxBy will instead return the entire complex object that has the maximum specified property.

See the example below where the Max statement returns 30, but the MaxBy statement we are able to return the Name of the person.
    
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.WriteLine(people.MaxBy(x => x.Age).Name);//Outputs Jane Smith
Console.WriteLine(people.Max(x => x.Age)); //Outputs 30


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