C# LINQ MaxBy — Complete Guide
In this tutorial, you'll learn about C# LINQ MaxBy. We cover key concepts, practical examples, and best practices.
You need the most expensive product, the oldest user, or the longest name. Max() returns only the value, not the element. You write a loop or use OrderByDescending + First. MaxBy (C# 9+) returns the element with the maximum key value in O(n) time.
Wrong
var mostExpensive = products[0];
for (int i = 1; i < products.Count; i++)
{
if (products[i].Price > mostExpensive.Price)
mostExpensive = products[i];
}
// Or:
var mostExpensive = products.OrderByDescending(p => p.Price).First();
Output: Works, but the loop is verbose and OrderByDescending + First is O(n log n) for an O(n) operation.
Right
var mostExpensive = products.MaxBy(p => p.Price);
Output: The Product with the highest Price. O(n) time, single pass.
MaxBy returns the first element with the maximum key if there are multiple:
var scores = new[] { (Name: "Alice", Score: 95), (Name: "Bob", Score: 95), (Name: "Charlie", Score: 80) };
var max = scores.MaxBy(s => s.Score);
// (Name: "Alice", Score: 95) — first occurrence
Prevention
- Use
MaxByto find the element with the maximum key value. - Use
Maxwhen you only need the key value, not the element. - Use
MinByfor the element with the minimum key. - Use
OrderByDescending+Firstwhen tie-breaking is important. - Use
MaxBywithIQueryablein EF Core 6+ for server-side evaluation. - Use
MaxBywith nullable keys — non-null values are considered greater than null.
Common Mistakes with linq max by
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
MaxBy is used in Doda Browser to find the most relevant search result by ranking score. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro