Distinct
suggest changeReturns unique values from an IEnumerable
. Uniqueness is determined using the default equality comparer.
int[] array = { 1, 2, 3, 4, 2, 5, 3, 1, 2 }; var distinct = array.Distinct(); // distinct = { 1, 2, 3, 4, 5 }
To compare a custom data type, we need to implement the IEquatable<T>
interface and provide GetHashCode
and Equals
methods for the type. Or the equality comparer may be overridden:
class SSNEqualityComparer : IEqualityComparer<Person> { public bool Equals(Person a, Person b) => return a.SSN == b.SSN; public int GetHashCode(Person p) => p.SSN; } List<Person> people; distinct = people.Distinct(SSNEqualityComparer);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents