65.9K
CodeProject is changing. Read more.
Home

Sorting using C# Lists

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (10 votes)

Feb 3, 2012

CPOL

1 min read

viewsIcon

151966

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;
        }
    }
}