How do you sort a C# array in descending or reverse order?  A simple way is to sort the array in ascending order, then reverse it:

1
2
3
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( array );
Array.Reverse( array );

Of course, this is not efficient for large arrays.

A better approach is to create a custom Comparer.  Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static public class ArraySorter<T>
    where T : IComparable
{
    static public void SortDescending( T[] array )
    {
        Array.Sort<T>( array, s_Comparer );
    }
    static private ReverseComparer s_Comparer = new ReverseComparer();
    private class ReverseComparer : IComparer<T>
    {
        public int Compare( T object1, T object2 )
        {
            return -((IComparable)object1).CompareTo( object2 );
        }
    }
}

Here’s a simple console program to test it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
 
namespace CSharp411
{
    class Program
    {
        static void Main( string[] args )
        {
            int[] array = new int[] { 3, 1, 4, 5, 2 };
            ArraySorter<int>.SortDescending( array );
            WriteArray( array );
            Console.ReadLine();
        }
        static private void WriteArray( int[] array )
        {
            foreach (int i in array)
            {
                Console.WriteLine( i );
            }
        }
    }
    static public class ArraySorter<T>
        where T : IComparable
    {
        static public void SortDescending( T[] array )
        {
            Array.Sort<T>( array, s_Comparer );
        }
        static private ReverseComparer s_Comparer = new ReverseComparer();
        private class ReverseComparer : IComparer<T>
        {
            public int Compare( T object1, T object2 )
            {
                return -((IComparable)object1).CompareTo( object2 );
            }
        }
    }
}