0

I search quite a number of examples regarding to this topic, and know that the class of the items in a List must inherit from the IComparable interface and override the CompareTo method if I want to use the Sort method of List.

My question is how can I define the sorting rules? Most of the examples I found sort numbers in ascending order.

Some examples suggest using Linq. I'm not familiar with it, so examples would make your explanation clearer, if you would also like to suggest me Linq. Thanks. ^^

chunchiu Chan
  • 199
  • 3
  • 14
  • 1
    List of what? Please provide example code. – Leon Jan 27 '15 at 07:47
  • I'm not sure what the question is, if you inherit the IComparable interface you specify the rules for the sorting in the CompareTo method. – joell Jan 27 '15 at 07:49
  • 1
    possible duplicate of [How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – DrKoch Jan 27 '15 at 07:50

1 Answers1

1

It is not necessary for class of the items in a list to implement IComparable.

You can use this override of List<T>.Sort, it takes Comparison<T> delegate as argument. So all comparing logic can be in that delegate.

Basically you can define comparing (sorting) rules as you want - but delegate should take two arguments and return integer less than 0 if first argument less than second, 0 if they are equals and integer greater than 0 otherwise.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71