LINQ Interview Question #65
What does Distinct do in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
Distinct removes duplicate elements according to the applicable equality comparison. For primitive values this is usually straightforward.
Detailed Explanation
Distinct removes duplicate elements according to the applicable equality comparison. For primitive values this is usually straightforward.
For custom objects, equality semantics determine whether two instances count as duplicates. DistinctBy can be convenient when uniqueness should be based on a selected key.
Code Example
var numbers = new[] { 1, 1, 2, 2, 3 };
var unique = numbers.Distinct();
// 1, 2, 3