C# LINQ MinBy — Complete Guide
In this tutorial, you'll learn about C# LINQ MinBy. We cover key concepts, practical examples, and best practices.
You need the cheapest product, the youngest user, or the shortest name. Min() returns only the value, not the element. You write a loop tracking both the min value and the element, or use Aggregate. MinBy (C# 9+) returns the element with the minimum key value.
Wrong
var cheapest = products[0];
for (int i = 1; i < products.Count; i++)
{
if (products[i].Price < cheapest.Price)
cheapest = products[i];
}
// Or:
var cheapest = products.OrderBy(p => p.Price).First();
Output: Works, but the loop is verbose and OrderBy + First is O(n log n) for an O(n) operation.
Right
var cheapest = products.MinBy(p => p.Price);
Output: The Product with the lowest Price. O(n) time, single pass.
MinBy returns the first element with the minimum key if there are multiple:
var scores = new[] { (Name: "Alice", Score: 90), (Name: "Bob", Score: 70), (Name: "Charlie", Score: 70) };
var min = scores.MinBy(s => s.Score);
// (Name: "Bob", Score: 70) — first occurrence
Prevention
- Use
MinByto find the element with the minimum key value. - Use
Minwhen you only need the key value, not the element. - Use
MaxByfor the element with the maximum key. - Use
OrderBy+Firstonly when you need a specific tie-breaking order. - Use
MinBywithIQueryablein EF Core 6+ for server-side evaluation. - Use
MinBywith nullable keys — null values are considered less than non-null.
Common Mistakes with linq min by
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
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
MinBy is used in Durga Antivirus Pro to find the smallest file signature match. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro