Aug 14
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:
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.
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:
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 );
}
}
}
}
Popularity: 32% [?]
Related posts:


This artical is very useful for me. I am a .NET developer and search for generic list sort decending.
Thanks
danks
Why reinvent the wheel … just use List and List.Reverse
hi,
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful for .Net community.
There is a good C# resource site, Have alook
http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html
simi
thanks. for this information about this program in C# …………………………
It's really a big help! Thanks author..