C# LINQ DistinctBy — Complete Guide
In this tutorial, you'll learn about C# LINQ DistinctBy. We cover key concepts, practical examples, and best practices.
You have a list of objects with duplicate Id values. Distinct() uses default equality — it only removes objects that are equal by reference or value. You want to remove duplicates based on a specific property. You write a GroupBy or a custom IEqualityComparer. DistinctBy (C# 9+) does it directly.
Wrong
var unique = users
.GroupBy(u => u.Id)
.Select(g => g.First())
.ToList();
Output: Works. But GroupBy + Select is verbose and allocates unnecessarily.
Right
var unique = users.DistinctBy(u => u.Id).ToList();
Output: Same result, one line. DistinctBy keeps the first element for each unique key.
The key selector can be any expression:
var uniqueByName = users.DistinctBy(u => u.Name.ToLowerInvariant()).ToList();
var uniqueByTuple = orders.DistinctBy(o => (o.CustomerId, o.ProductId)).ToList();
Prevention
- Use
DistinctByinstead ofGroupBy+Firstfor deduplication by key. - Use
DistinctBywithIQueryablefor server-side deduplication in EF Core (supported in EF Core 6+). - Use
DistinctBywith a tuple key for composite deduplication. - Use
Distinct()when removing full-object duplicates (no key selector needed). - Use a custom
IEqualityCompareronly whenDistinctBydoes not support the needed comparison logic. - Remember that
DistinctByis LINQ to Objects — it does not translate to SQL in all providers.
Common Mistakes with linq distinct 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
DistinctBy is used in Doda Browser to deduplicate extension search results by extension ID. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro