Reverse a complex type

Joined
Apr 22, 2016
Messages
8
Programming Experience
1-3
I have just finished learning how to use ICompare and IComparable to sort complex-types and I can now use .Sort() on my classes.

I want to know how to make .Reverse() also work on my classes.

Kind regards

Richard.
 
You don't need to do anything because reversing an array or a List (which uses Array.Reverse internally anyway) simply reverses the current order of the items, whatever that may be. There's no comparing to be done so the items don't even need to be comparable. In short, if you want to reverse an array or List of your type then simply call Reverse and you're done.
 
Thanks,

As a follow up question, when I implement the Sort using Comparison<class-type> and using a delegate, am I correct in thinking that I do not need the IComparable or IComparer?

Regards

Richard.
 
Thanks,

As a follow up question, when I implement the Sort using Comparison<class-type> and using a delegate, am I correct in thinking that I do not need the IComparable or IComparer?

Regards

Richard.

That is correct. Sorting is achieved by repeatedly comparing pairs of items and rearranging them if appropriate. As a result, what is required to sort is a method that can take two items, compare them and return a value indicating whether they should be rearranged or not. If the items implement IComparable then that method is contained in the items themselves. If you implement IComparer then that method is contained in the implementing type. If you use a Comparison delegate then that method is the one it refers to. They are just three different ways of providing the list doing the sorting with a method to compare the items it contains.
 
Back
Top Bottom