Distinct C# with Example



Distinct C# with Example

Returns 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 interface and provide GetHashCode and 
Equals methods for the type. Or the equality comparer may be overridden: 
class SSNEqualityComparer : IEqualityComparer { 
public bool Equals(Person a, Person b) => return a.SSN == b.SSN; 
public int GetHashCode(Person p) => p.SSN; 
} 
List people; 
distinct = people.Distinct(SSNEqualityComparer); 

0 Comment's

Comment Form

Submit Comment