6

The CompareTo() method for my class is dynamic, and can range from a simple comparison to comparisons on a number of columns. This is all determined at run time, and it works great.

But in some cases, I want any attempt to sort a collection of my objects using the default comparison to just do nothing.

Having CompareTo() just return a 0 for any comparison, to my surprise, doesn't work. The list gets rearranged in some odd, seemingly-random order.

Is there a way to do this in the CompareTo() method implementation? I'd rather not handle this up at the collection level by having to override Sort().

richardtallent
  • 34,724
  • 14
  • 83
  • 123

3 Answers3

1

That's because QuickSort is not a stable sort. I don't see a good option to fix this in the CompareTo method unless you can somehow obtain the index of the element.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

I haven´t proved it, but as a suggestion, what if you try to return always 1, or always -1?

Javier
  • 4,051
  • 2
  • 22
  • 20
  • 2
    This violates the properties of the CompareTo method: If A.CompareTo(B) returns a value other than zero, then B.CompareTo(A) is required to return a value of the opposite sign. – Kevin Crowell Mar 09 '10 at 23:52
0

You have to override Sort(). The default implementation of Sort() offers no guarantees about how it will use CompareTo() to arrive at a sorted collection, so there isn't any way to use it to make Sort() do the right thing.

David Seiler
  • 9,557
  • 2
  • 31
  • 39