Re: IComparable.CompareTo not being called on Array.Reverse
From: Justin Rogers (Justin_at_games4dotnet.com)
Date: 07/01/04
- Next message: Kevin Aubuchon: "Re: Property"
- Previous message: morgal: "Data passing between projects in a solution"
- In reply to: Brian W: "IComparable.CompareTo not being called on Array.Reverse"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 1 Jul 2004 16:16:25 -0700
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.
-- Justin Rogers DigiTec Web Consultants, LLC. Blog: http://weblogs.asp.net/justin_rogers "Brian W" <brianw@gold_death_2_spam_rush.com> wrote in message news:entMo17XEHA.3564@TK2MSFTNGP11.phx.gbl... > 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 > > > > > > >
- Next message: Kevin Aubuchon: "Re: Property"
- Previous message: morgal: "Data passing between projects in a solution"
- In reply to: Brian W: "IComparable.CompareTo not being called on Array.Reverse"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|