Click here to Skip to main content
Click here to Skip to main content

Tagged as

Sorting using C# Lists

, 31 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

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.

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)

Share

About the Author

Dhanushka Madushan lk
Software Developer
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

 
Generalthanks Pinmemberarvindps20-Jan-13 5:06 
SuggestionSuggestion PinmemberDhanushka Madushan lk4-Apr-12 21:27 
QuestionKeep it simple: use OrderBy/OrderByDescending instead... PinmemberAndreas Gieriet4-Apr-12 0:53 
AnswerRe: Keep it simple: use OrderBy/OrderByDescending instead... Pinmember ProgramFOX16-Jan-13 6:29 
GeneralRe: Keep it simple: use OrderBy/OrderByDescending instead... PinmemberAndreas Gieriet27-Jan-13 4:49 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 31 Mar 2012
Article Copyright 2012 by Dhanushka Madushan lk
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid