Equals and GetHashCode in IEqualityComparator C# with Example



Equals and GetHashCode in IEqualityComparator C# with Example

For given type Person: 
public class Person 
{ 
public string Name { get; set; } 
public int Age { get; set; } 
public string Clothes { get; set; } 
} 
List persons = new List 
{ 
new Person{ Name = "Jon", Age = 20, Clothes = "some clothes"}, 
new Person{ Name = "Dave", Age = 20, Clothes = "some other clothes"}, 
new Person{ Name = "Jon", Age = 20, Clothes = ""} 
}; 
var distinctPersons = persons.Distinct().ToList();//  distinctPersons  has  Count  =  3 
But defining Equals and GetHashCode into an IEqualityComparator : 
public class PersonComparator : IEqualityComparer 
{ 
public bool Equals(Person x, Person y) 
{ 
return x.Name == y.Name && x.Age == y.Age; //the clothes are not important when comparing 
 

two persons; 
} 
public int GetHashCode(Person obj) { return obj.Name.GetHashCode() * obj.Age; } 
} 
var distinctPersons = persons.Distinct(new PersonComparator()).ToList();// distinctPersons has 
Count = 2 
Note that for this query, two objects have been considered equal if both the Equals returned true and the 
GetHashCode have returned the same hash code for the two persons. 
 

Parameter Details 
possibleNullObject 
The value to test for null value. If non null, this value is returned. Must be a nullable type. 
The value returned if possibleNullObject is null. Must be the same type as 
defaultValue 
possibleNullObject. 

0 Comment's

Comment Form

Submit Comment