LINQ Interview Question #137
How can LINQ remove duplicate objects based on one property?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
DistinctBy can return the first element for each distinct key. Alternatively, GroupBy followed by selecting one element from each group can implement similar behavior.
Detailed Explanation
DistinctBy can return the first element for each distinct key. Alternatively, GroupBy followed by selecting one element from each group can implement similar behavior.
Which record should survive must be defined when duplicates differ in other properties. Ordering before DistinctBy can make the selection rule explicit.
Code Example
var uniqueUsers = users
.OrderByDescending(u => u.UpdatedAt)
.DistinctBy(u => u.Email)
.ToList();