Posts

Showing posts with the label IEqualityComparer<T>

Donate

How To Remove Duplicate Items In A List<T> Using IEqualityComparer<T>

Image
Good evening. Here's a simple demo on how to remove duplicate items in a List object using IEqualityComparer given that the generic list's type is complex. First we setup a simple model Employee class with Age, Name and Address properties. class Employee { public int Age { get ; set ; } public string Name { get ; set ; } public string Address { get ; set ; } } Next is to create a comparer class that implements IEqualityComparer interface. class EmployeeComparer : IEqualityComparer<Employee> { public bool Equals(Employee emp1, Employee emp2) { if (Object.ReferenceEquals(emp1, emp2)) return true ; if (Object.ReferenceEquals(emp1, null ) || Object.ReferenceEquals(emp2, null )) return false ; return (emp1.Age == emp2.Age) && (emp1.Name == emp2.Name) && (emp1.Address == emp2.Address); } public int GetHashCode(Employee obj) {

Donate