Home > C#/.Net/ASP.Net > Custom Sorting with IComparer

Custom Sorting with IComparer

Sorting is a common operation we perform frequently while writing code. We sort a set of data of some type, sometimes for efficient searching, sometimes for representing data in a more meaningful form and sometimes for some other purpose.

In .Net, there are several different ways to sort a set of data, namely a collection. You can use the Sort method of System.Array class to sort an array. Or you can use the generic Sort<T> method of System.Array class to sort an array of type T. These are good enough if you are sorting a collection of items of a basic type such as int, string etc. But, what if the collection to be sorted contains items of a complex type or you want to sort the items in descending order? Then you need to customize the sorting operation.

Since we are talking about comparison-based sorting, we should customize the comparison operation of Sort methods. This can be done by defining a custom comparer class that implements the IComparer interface. Then you can pass an instance of your comparer class as an argument to one of the Sort methods. This way, the Sort method will try to sort the collection using the Compare method implementation of your comparer class.

The following C# code demonstrates how to sort an array of strings in descending order using a custom comparer class:

class Program
{
    class CustomStringComparerDescending : IComparer<string>
    {
        int IComparer<string>.Compare(string x, string y)
        {
            return string.Compare(y, x);
        }
    }
    static void Main(string[] args)
    {
        string[] arr = new string[] {"string-1", "string-2", "string-3"};

        Console.WriteLine("[before]");
        foreach (string str in arr)
        {
            Console.WriteLine(str);
        }
        // sort the array using "CustomStringComparerDescending"
        Array.Sort<string>(arr, new CustomStringComparerDescending());

        Console.WriteLine("[after]");
        foreach (string str in arr)
        {
            Console.WriteLine(str);
        }
    }
}

Check this demo application for more custom sorting examples:

Customized Sorting with IComparer Demo Application

Customized Sorting with IComparer Demo Application

Download the source code

Categories: C#/.Net/ASP.Net Tags: ,
  1. March 23rd, 2010 at 13:27 | #1

    Very good share. Thank you very much Ardal.
    We expect the new samples. :-)

  1. No trackbacks yet.