11

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?

Gary Willoughby
  • 50,926
  • 41
  • 133
  • 199

4 Answers4

14

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

Kevin Crowell
  • 10,082
  • 4
  • 35
  • 51
  • +1 although you could write that more succinctly with a lambda expression :) – Mark Seemann Mar 19 '10 at 19:54
  • Kevin, I've struggled with this for 2 days now, and I can't understand what it is doing. Your way does work, but how would this static method be written without writing it as `delegate`? –  Mar 22 '13 at 16:21
  • 1
    @jp2code This answer actually got me thinking more deeply about comparisons. I asked a question about it, and I really like the accepted answer. See if that helps you out: http://stackoverflow.com/questions/2488298/advantages-disadvantages-of-different-implementations-for-comparing-objects-usin – Kevin Crowell Mar 22 '13 at 20:47
9

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

CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58
  • I upvoted this answer as Kevin's because I think they are both good solutions. I used this solution because I think it is simpler. itemDescription/ItemNumber: I have provided an answer that demonstrates my implementation – Mark Ainsworth Sep 06 '15 at 18:30
3

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
2

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.

Achim
  • 15,415
  • 15
  • 80
  • 144