Click here to Skip to main content
15,879,239 members
Articles / Programming Languages / C#
Tip/Trick

Sorting using C# Lists

Rate me:
Please Sign up or sign in to vote.
4.67/5 (11 votes)
31 Mar 2012CPOL1 min read 150.3K   11   5
Sorting using C# Lists.

When you have an Array or List<> of types such as string or integer that already support IComparer, you can sort that array or list without providing any explicit reference to IComparer. In that case, the elements of the array are cast to the default implementation of IComparer (Comparer.Default) for you.

C#
List<string> list = new List<string>();
//Sort alphabetically, in ascending order (A - Z)
list.Sort();

But when you have user defined objects, you must implement either or both of these interfaces:

  1. IComparable
  2. IComparer

IComparable

C#
namespace sorting
{
    class Program
    {
        public static List<student> students = new List<student>(); //list object

        static void Main(string[] args)
        {
            students.Add(new student("Yeshani", 22));
            students.Add(new student("Dhanushka", 25));
            students.Add(new student("Madushan", 27));
            students.Sort();
            foreach (student n in students)
            {
                Console.WriteLine(n.name);
            }
            Console.ReadLine();
                   
        }
    }

    public class student:IComparable<student>
    {
        public string name;
        public int age;
        public student(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public int CompareTo(student b)
        {
            // Alphabetic sort name[A to Z]
            return this.name.CompareTo(b.name);
        }
    
    }
}

When a class implements the IComparable interface, we must also implement the public method CompareTo(T). In the CompareTo method, we can write our sorting algorithm. In here I have sorted the list on student name alphabetically.

We use IComparable<T> when the class has an intrinsic comparison. We need to know the sorting criteria before we start. In here we have to decide whether to sort on age or name before we implement the class. But in some situations we may need various kinds of sorting on a class.

To solve this problem, .NET provides a special interface called IComparer<> which has a method Compare(), that takes two object parameters X, Y and returns an int. The use of the IComparer<> interface tells List how exactly you want to sort.

IComparer

We use IComparer when you want a comparison method other than the class intrinsic comparison, if it has one.

C#
namespace sorting
{
    class Program
    {
        public static List<student> students = new List<student>(); //list object

        static void Main(string[] args)
        {
            students.Add(new student("Yeshani", 22));
            students.Add(new student("Dhanushka", 25));
            students.Add(new student("Madushan", 27));

            sortOnAge soa = new sortOnAge();
            students.Sort(soa);
            foreach (student n in students)
            {
                Console.WriteLine(n.name);
            }
            Console.ReadLine();
                   
        }
    }

    public class student:IComparable<student>
    {
        public string name;
        public int age;
        public student(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public int CompareTo(student b)
        {
            // Alphabetic sort name[A to Z]
            return this.name.CompareTo(b.name);
        }
    
    }

    public class sortOnAge : IComparer<student>
    {
        public int Compare(student a, student b)
        {
            if (a.age > b.age) return 1;
            else if (a.age < b.age) return -1;
            else return 0;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalthanks Pin
arvindps20-Jan-13 4:06
arvindps20-Jan-13 4:06 
SuggestionSuggestion Pin
Dhanushka Madushan lk4-Apr-12 20:27
Dhanushka Madushan lk4-Apr-12 20:27 
QuestionKeep it simple: use OrderBy/OrderByDescending instead... PinPopular
Andreas Gieriet3-Apr-12 23:53
professionalAndreas Gieriet3-Apr-12 23:53 
AnswerRe: Keep it simple: use OrderBy/OrderByDescending instead... Pin
Thomas Daniels16-Jan-13 5:29
mentorThomas Daniels16-Jan-13 5:29 
GeneralRe: Keep it simple: use OrderBy/OrderByDescending instead... Pin
Andreas Gieriet27-Jan-13 3:49
professionalAndreas Gieriet27-Jan-13 3:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.