C#

How can I get LINQ to return the object which has the max value for a given property duplicate

27 September 2026 · 6 min read

How can I get LINQ to return the object which has the max value for a given property duplicate

When working with collections in C, developers often leverage Language Integrated Query (LINQ) for powerful and concise data manipulation. A common scenario involves needing to extract not just the maximum value of a specific property within a collection, but the entire object that possesses that maximum value. While LINQ’s Max() method readily provides the highest value, it doesn’t directly return the corresponding object. This article explores several effective strategies for how you can get LINQ to return the object which has the max value for a given property, offering practical examples and discussing the nuances of each approach to help you choose the best fit for your application. We’ll dive into built-in LINQ operations, external libraries, and even custom extension methods to solve this frequent programming challenge.

Using OrderByDescending and FirstOrDefault for Simplicity

One of the most straightforward and commonly used approaches to retrieve the object with the maximum property value is to combine LINQ’s OrderByDescending and FirstOrDefault methods. This strategy involves sorting the entire collection based on the desired property in descending order and then simply selecting the very first element from the sorted sequence. This method is highly readable and intuitive, making it an excellent choice for many everyday scenarios.

For instance, imagine you have a list of products, and each product has a Price property. If you want to find the most expensive product, you would sort the list by Price in descending order. The product at the top of this sorted list would naturally be the one with the highest price. This technique is particularly effective when dealing with moderately sized collections where the overhead of sorting doesn’t significantly impact performance.

To efficiently get LINQ to return the object which has the max value for a given property, you can use OrderByDescending() on the property you’re interested in, followed by FirstOrDefault(). This sequence ensures the collection is sorted from highest to lowest based on your criteria, and then selects the first element, which will be the object possessing that maximum value.

public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int StockQuantity { get; set; } } List<Product> products = new List<Product> { new Product { Id = 1, Name = "Laptop", Price = 1200.00m, StockQuantity = 50 }, new Product { Id = 2, Name = "Mouse", Price = 25.00m, StockQuantity = 200 }, new Product { Id = 3, Name = "Keyboard", Price = 75.00m, StockQuantity = 150 }, new Product { Id = 4, Name = "Monitor", Price = 350.00m, StockQuantity = 75 }, new Product { Id = 5, Name = "External SSD", Price = 1200.00m, StockQuantity = 30 } }; // Find the product with the maximum price Product mostExpensiveProduct = products .OrderByDescending(p => p.Price) .FirstOrDefault(); if (mostExpensiveProduct != null) { Console.WriteLine($"Most expensive product: {mostExpensiveProduct.Name} (Price: {mostExpensiveProduct.Price:C})"); } else { Console.WriteLine("No products found."); } 

While highly readable, it’s important to note that OrderByDescending will sort the entire collection, which can be less performant for very large datasets compared to approaches that only iterate once. However, for most common business applications, the performance overhead is negligible, and the code clarity often outweighs this minor consideration.

Leveraging the MaxBy Method (MoreLINQ Library)

For those seeking a more specialized and often more performant solution, the MoreLINQ library provides an excellent extension method called MaxBy (and its counterpart, MinBy). MoreLINQ is a collection of useful LINQ extension methods that complement the standard LINQ operators, filling in common gaps and offering optimized implementations for frequent scenarios. The MaxBy method is specifically designed to return the element (or elements, if there are ties) from a sequence that has the maximum value for a specified property.

Using MaxBy significantly simplifies the code required to get LINQ to return the object which has the max value for a given property. Instead of a two-step process of sorting and then picking the first element, MaxBy achieves this in a single, expressive call. This method is particularly beneficial because it typically involves only a single pass through the collection, making it more efficient than a full sort for very large collections, especially when you only need the single maximum element.

// First, install MoreLINQ via NuGet: // Install-Package MoreLINQ using MoreLinq; // Required namespace // ... (Product class and products list as above) ... // Find the product with the maximum price using MaxBy Product mostExpensiveProductMoreLINQ = products.MaxBy(p => p.Price); if (mostExpensiveProductMoreLINQ != null) { Console.WriteLine($"Most expensive product (MoreLINQ): {mostExpensiveProductMoreLINQ.Name} (Price: {mostExpensiveProductMoreLINQ.Price:C})"); } else { Console.WriteLine("No products found."); } 

The MaxBy method offers a clean, concise, and often more performant way to achieve the desired result. It’s a testament to the power of well-designed extension methods that can enhance the expressiveness and efficiency of LINQ queries. If you frequently find yourself needing to retrieve an object based on a maximum or minimum property value, integrating MoreLINQ into your project can be a significant productivity booster.

Implementing a Custom Extension Method for Control

While OrderByDescending().FirstOrDefault() is simple and MaxBy from MoreLINQ is efficient, there might be scenarios where you prefer not to add an external dependency or want to understand the underlying logic deeply. In such cases, crafting your own custom LINQ extension method to return the object which has the max value for a given property provides ultimate control and flexibility. This approach allows you to tailor the logic precisely to your needs, including handling edge cases like empty collections or ties.

A common way to implement a custom MaxBy equivalent is by iterating through the collection once, keeping track of the current maximum value and the corresponding object. This single-pass approach ensures optimal performance, similar to the MoreLINQ version. For instance, you could use an AggregateQuestion & Answer :

If I have a class that looks like:
public class Item { public int ClientID { get; set; } public int ID { get; set; } } 

And a collection of those items…

List<Item> items = getItems(); 

How can I use LINQ to return the single “Item” object which has the highest ID?

If I do something like:

items.Select(i => i.ID).Max(); 

I’ll only get the highest ID, when what I actually want returned is the Item object itself which has the highest ID? I want it to return a single “Item” object, not an int.

This will loop through only once.

Item biggest = items.Aggregate((i1,i2) => i1.ID > i2.ID ? i1 : i2); 

Thanks Nick - Here’s the proof

class Program { static void Main(string[] args) { IEnumerable<Item> items1 = new List<Item>() { new Item(){ ClientID = 1, ID = 1}, new Item(){ ClientID = 2, ID = 2}, new Item(){ ClientID = 3, ID = 3}, new Item(){ ClientID = 4, ID = 4}, }; Item biggest1 = items1.Aggregate((i1, i2) => i1.ID > i2.ID ? i1 : i2); Console.WriteLine(biggest1.ID); Console.ReadKey(); } } public class Item { public int ClientID { get; set; } public int ID { get; set; } } 

Rearrange the list and get the same result