When to use IComparable Vs. IComparer

前端 未结 8 1228
[愿得一人]
[愿得一人] 2020-11-29 16:07

I\'m trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?

相关标签:
8条回答
  • 2020-11-29 16:55

    IComparable says an object can be compared with another. IComparer is an object that can compare any two items.

    0 讨论(0)
  • 2020-11-29 16:59

    IComparer is a interface which is used to sort the Array, this interface will force the class to implement the Compare(T x,T y) method, which will compare the two objects. The instance of the class which implemented this interface is used in the sorting of the Array.

    IComparable is a interface is implemented in the type which needs to compare the two objects of the same type, This comparable interface will force the class to implement the following method CompareTo(T obj)

    IEqualityComparer is a interface which is used to find the object whether it is Equal or not, Now we will see this in a sample where we have to find the Distinct of a Object in a collection. This interface will implement a method Equals(T obj1,T obj2)

    Now we take a Example we have a Employee class , based on this class we have to create a Collection. Now we have the following requirements.

    Sort the Array using Array class 2. Need an collection using Linq : Remove the Duplicate, Order by higher to lower, Remove one employee id

    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 EmployeeIdSorter : IComparer { public int Compare(Employee x, Employee y) { if (x.Id < y.Id) return 1; else if (x.Id > y.Id) return -1; else return 0; } }

        public class EmployeeSalarySorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Salary < y.Salary)
                    return 1;
                else if (x.Salary > y.Salary)
                    return -1;
                else
                    return 0;
            }
        }
    

    For more info refere below http://dotnetvisio.blogspot.in/2015/12/usage-of-icomparer-icomparable-and.html

    0 讨论(0)
提交回复
热议问题