Implement IEqualityComparer

后端 未结 3 1039
Happy的楠姐
Happy的楠姐 2021-02-14 09:38

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

3条回答
  •  心在旅途
    2021-02-14 10:29

    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

提交回复
热议问题