Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class that implements IComparable.

public class MyClass : IComparable<MyClass>
{
    public int CompareTo(MyClass c)
    {
        return this.whatever.CompareTo(c.whatever);
    }

    etc..
}

I then can call the sort method of a generic list of my class

List<MyClass> c = new List<MyClass>();
//Add stuff, etc.

c.Sort();

and have the list sorted according to my comparer.

How do i specify further comparers to sort my collection different ways according to the other properties of MyClass in order to let users sort my collection in a number of different ways?

like image 407
Gary Willoughby Avatar asked Mar 19 '10 19:03

Gary Willoughby


3 Answers

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 :)

like image 120
Kevin Crowell Avatar answered Sep 19 '22 00:09

Kevin Crowell


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

like image 29
CookieOfFortune Avatar answered Sep 19 '22 00:09

CookieOfFortune


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.

like image 29
Mark Seemann Avatar answered Sep 18 '22 00:09

Mark Seemann