views:

207

answers:

3

Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?

+3  A: 

You need to pass a IComparer object or Comparison delegate to the Sort function.

Here is a sample code from C# 2.0

   Array.Sort(array,delegate(string a, string b)
    {
        return b.CompareTo(a);
    });

EDIT: missed the array bit.

Michał Piaskowski
Why not simply return b.CompareTo(a)?
Chris Marasti-Georg
Yeah, that's better.
Michał Piaskowski
There are actually two important differences here:1) What should happen to null strings? Often when reversing comparisons you *don't* want to reverse what happens to nulls. Just a thought. 2) Returning -a.CompareTo(b) (i.e. pre-edit) causes problems if int.MinValue is returned by a.CompareTo(b).
Jon Skeet
I'm pretty sure most string sorting algorithms, like this one, would throw NullReferenceExceptions if there is a null value in the list. However, the point you bring up in #1 remains for empty strings.
Chris Marasti-Georg
+11  A: 

Provide an appropriate element comparer. What C# version do you use? 3 lets you do this:

Array.Sort(myarray, (a, b) => b.CompareTo(a));
Konrad Rudolph
+1  A: 

if you use a different comparitor that is the reverse of the standard that would do it.

Alternatively sort it normally and then reverse it...

Omar Kooheji