I would like to get distinct objects from a list. I tried to implement IEqualityComparer
but wasn\'t successful. Please review my code and give me an explanation fo
IEqualityComparer
is an interface which is used to find whether an object is equal or not. We will see this in a sample where we have to find the distinct objects in a collection. This interface will implement the method Equals(T obj1,T obj2)
.
abstract public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { set; get; }
}
public enum SortType
{
ByID,
BySalary
}
public class EmployeeDistinctEquality : IEqualityComparer
{
public EmployeeDistinctEquality()
{
}
public bool Equals(Employee x, Employee y)
{
if (x == null && y == null)
return true;
else if (x == null || y == null)
return false;
else if (x.Id == y.Id)
return true;
else
return false;
}
public int GetHashCode(Employee obj)
{
return obj.Id.GetHashCode();
}
}
Refer to this link for more detailed information:
http://dotnetvisio.blogspot.in/2015/12/usage-of-icomparer-icomparable-and.html