LINQ MaxBy

Summary: in this tutorial, you will learn how to use the LINQ MaxBy() method to return the element with the maximum value in a sequence.

Introduction to the LINQ MaxBy() method

The MaxBy() method returns the maximum value in a sequence based on a key selector function:

TSource? MaxBy<TSource,TKey> (
    this Enumerable<TSource> source, 
    Func<TSource,TKey> keySelector
);Code language: C# (cs)

In this syntax;

  • TSource is the type of element in the source sequence.
  • TKey is a type of key used to compare elements.
  • source is an input sequence of elements with IEnumerable<TSource> type.
  • keySelector is a function that extracts the key for each element.

The LINQ MaxBy() returns the value with the maximum key in the sequence.

Note that the Max() method returns the maximum value of elements by a key while the MaxBy() method returns the element with the maximum value by the key.

LINQ MaxBy() method examples

Suppose you have a Product class that has three properties Name, Cost, and Price:

public class Product
{
    public string Name
    {
        get; set;
    }

    public decimal Price
    {
        get; set;
    }

    public decimal Cost
    {
        get; set;
    }

    public Product(string name, decimal cost, decimal price)
    {
        Name = name;
        Cost = cost;
        Price = price;
    }

    public override string ToString() => $"{Name}, Cost:{Cost}, Price:{Price}";
}Code language: C# (cs)

The following program uses the MaxBy() method to find the product that has the highest price:

using static System.Console;

var products = new List<Product>() {
    new Product(name:"A",cost:100,price:160),
    new Product(name:"B",cost:95,price:130),
    new Product(name:"C",cost:140,price:150),
};

var product = products.MaxBy(p => p.Price);

WriteLine(product);Code language: C# (cs)

Output:

A, Cost:100, Price:160Code language: C# (cs)

It returns product A with a price of 160.

To find the product with the highest cost, you change the key selector function to select the Cost property instead of Price property as follows:

using static System.Console;

var products = new List<Product>() {
    new Product(name:"A",cost:100,price:160),
    new Product(name:"B",cost:95,price:130),
    new Product(name:"C",cost:140,price:150),
};

var product = products.MaxBy(p => p.Cost);

WriteLine(product);Code language: C# (cs)

Output:

C, Cost:140, Price:150Code language: C# (cs)

Summary

  • Use the LINQ MaxBy() method to return the element with the maximum value in a sequence.
Was this tutorial helpful ?