Scott
Scott

Reputation:

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

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

Upvotes: 5

Views: 393

Answers (3)

Michał Piaskowski
Michał Piaskowski

Reputation: 3850

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.

Upvotes: 3

Omar Kooheji
Omar Kooheji

Reputation: 55770

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

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545963

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

Array.Sort(myarray, (a, b) => b.CompareTo(a));

Upvotes: 11

Related Questions