IComparable.CompareTo not being called on Array.Reverse

B

Brian W

Because of the upcoming US holiday I'll probably have to ask this again next
week, but just on the off-chance, I'll ask anyway


I have a class defined something like this...

public class Item : IComparable
{
private string _name;
// ... more stuff here
public int CompareTo(object obj)
{
// I put a break point below to test this...
return _name.CompareTo(((Item)obj)._name;
}
}

Then. elsewhere I have an array of Item

Item[] items = new Item[5];
//Fill the array blah, blah, blah

Now, when I want to sort I do this...

Array.Sort(items);

and voila! the array is sorted, and in doing so, the break point is hit in
the CompareTo method

OK, let's say I wanted it Reverse sorted so I do this...

Array.Reverse(items);

I get no errors or exceptions and the array is returned to me in the same
state/order it went in.

AND the break point is never hit in CompareTo

Am I doing something wrong or is Reverse broken, or am I completely
misunderstanding something.


TIA
Brian W
 
J

Justin Rogers

Reverse does NOT do a sorted reverse. Instead it just reverses the
array as it already appears. If you need a sorted reverse you'll have
to sort first, then do a reverse. Even better is to use an IComparer
that you can pass to Array.Sort that allows for bidirectional sorting
depending on some flag you set. That way you only perform a single
operation.

As an example...

1 2 3 5 7 11 in an integer array. Now mix them up a bit
7 5 3 2 1 11 is the new array. Now reverse it
11 1 2 3 5 7 is the reversed array. This is not a sorted reverse. Sort
1 2 3 5 7 11 is the sorted array, now reverse.
11 7 5 3 2 1 is the reversed array.

Hopefully that details how everything works. With the custom
comparer you can do something like:

myComparer.Ascending = true;
Array.Sort(myArray, myComparer); // Sorts ascending
myComparer.Ascending = false;
Array.Sort(myArray, myComparer); // Sorts in reverse order now

You'll have to check the flag in your comparison routine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top