LINQ Interview Question #66
What is DistinctBy in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
DistinctBy returns the first element for each distinct key selected from the source. It is useful when objects should be deduplicated by a property rather than by their complete equality definition.
Detailed Explanation
DistinctBy returns the first element for each distinct key selected from the source. It is useful when objects should be deduplicated by a property rather than by their complete equality definition.
The order of the source can therefore matter because the first element encountered for a key is retained.
Code Example
var uniqueByEmail = users
.DistinctBy(u => u.Email);
var uniqueProducts = products
.DistinctBy(p => p.Sku);