C# - How to implement multiple comparers for an IComparable class?

后端 未结 4 1360
时光取名叫无心
时光取名叫无心 2020-12-30 08:22

I have a class that implements IComparable.

public class MyClass : IComparable
{
    public int CompareTo(MyClass c)
    {
        return this         


        
相关标签:
4条回答
  • 2020-12-30 08:32

    If you have multiple ways to sort a list of your objects, you obviously have to specify which option to choose. That's what the other overrides of Sort are good for. Have a look at IComparer and Comparison.

    0 讨论(0)
  • 2020-12-30 08:43

    One step in that direction would be to use the Sort overload that let's you specify an IComparer<T> (not an IComparable<T>, though).

    If you already have a lot of IComparable<T> implementations, it should be trivial to write a general-purpose implementation of IComparer<T> that compares two IComparable<T> instances. In fact, I'm a bit surprised such a class doesn't already exist in the BCL, but I haven't been able to find one.

    Comparer<T>.Default comes close, but not quite.

    0 讨论(0)
  • 2020-12-30 08:47

    To setup the sort in your class:

    public static Comparison<MyClass> OtherComparison = delegate(MyClass object1, MyClass object2)
    {
        return object1.Whatever.CompareTo(object2.Whatever);
    };
    

    Then to sort using your new comparison:

    List<MyClass> myClassList = new List<MyClass>();
    myClassList.Sort(MyClass.OtherComparison);
    

    Except you clearly will not want to sort an empty list :)

    0 讨论(0)
  • 2020-12-30 08:48

    You can call Sort with a specific comparer as the argument. Reference: MSDN

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