views:

126

answers:

3

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().

A: 

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

Javier Morillo
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
Understood. Thanks @Kevin
Javier Morillo
A: 

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
+1  A: 

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
Thanks, makes perfect sense. I expected that was the case, but Data Algorithms class was so long ago...
richardtallent