Wednesday, October 14, 2009

Sort Object ArrayList in C#


You can easily sort an arraylist using its "sort()" method, but how can you sort an ArrayList of Objects? You can get this task done very easily with "IComparer" Interface.

As an example let’s get a "Person" object which contains two attributes called "ID" and "Name". Now we need to sort these objects by "ID" or "Name". By looking at the following picture, you can get very clear idea about what we are going to do now.

You may notice in "Sort 2" first I have sort by "ID" and then by "Name". I’ll give you the C# code for the above task using simple console application.

Create new class called "Person" and paste this code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortArrayList
{
    class Person
    {
        private int id;
        public int ID
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int CompareTo(Person psn2, ObjCompare.ComparisonType comparisonType, Person psn1)
        {
            int returnValue;
            if (comparisonType == ObjCompare.ComparisonType.ID)
            {
                if (psn1.ID == psn2.ID)
                {
                    returnValue = Name.CompareTo(psn2.Name);
                }
                else
                {
                    returnValue = ID.CompareTo(psn2.ID);
                }
            }
            else if (comparisonType == ObjCompare.ComparisonType.Name)
            {
                returnValue = Name.CompareTo(psn2.Name);
            }
            else
            {
                returnValue = ID.CompareTo(psn2.ID);
            }
            return returnValue;
        }
    }
}

Create new class called "ObjCompare" and paste this code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList
{
    class ObjCompare : IComparer
    {
        public enum ComparisonType
        {
            ID, Name
        }
        private ComparisonType compMethod;
        public ComparisonType ComparisonMethod
        {
            get { return compMethod; }
            set { compMethod = value; }
        }
        public int Compare(object x, object y)
        {
            Person psn1 = (Person)x;
            Person psn2 = (Person)y;
            return psn1.CompareTo(psn2, ComparisonMethod, psn1);
        }
    }
}

Now update your "Programme.cs" as bellow;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SortArrayList
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList lst = new ArrayList();

            Person psn = new Person();
            psn.Name = "Jack"; psn.ID = 15;
            lst.Add(psn);

            Person psn1 = new Person();
            psn1.Name = "David"; psn1.ID = 18;
            lst.Add(psn1);

            Person psn2 = new Person();
            psn2.Name = "Daniel"; psn2.ID = 12;
            lst.Add(psn2);

            Person psn3 = new Person();
            psn3.Name = "Owen"; psn3.ID = 20;
            lst.Add(psn3);

            Person psn4 = new Person();
            psn4.Name = "Colin"; psn4.ID = 16;
            lst.Add(psn4);

            Person psn5 = new Person();
            psn5.Name = "Aiden"; psn5.ID = 18;
            lst.Add(psn5);

            Console.Write(" ---before sort --- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
            /* sorting */
            ObjCompare objcom = new ObjCompare();
            objcom.ComparisonMethod = ObjCompare.ComparisonType.ID;
            lst.Sort(objcom);

            Console.Write(" ---after sort -- \n");
            foreach (Person item in lst)
            {
                int id = item.ID;
                string ttl = item.Name;
                Console.Write(id + " " + ttl + "\n");
            }
        }
    }
}

You will get the output as "Sort 2" in the picture. If you don't want to sort by "Name" you can do it by editing "Person" class. There I have check whether "psn1.ID == psn2.ID", by commenting that part you can get the result as "Sort 1".

3 comments:

  1. Thank you so much! Worked like a charm... I modified it for sorting by distance...

    ReplyDelete
  2. Quite an interesting code for sorting. Works fine. Please post with modifications for Windows Forms application:
    1. Use the user input in text boxes for the array, say Name, Age.
    2. Output result in ascending order to another set of text boxes in the
    same user form.
    I have gone through a couple of text books. I don't get a clue.
    I am looking forward to your help in this regard.
    Ramabhadran NK (nkrb1941@gmail.com)

    ReplyDelete
  3. THANK YOU! I'm learning C# and had to create an ArrayList of objects. I then needed to sort them and had so much trouble figuring out how to sort objects, not just an array list of strings. This was so helpful!!

    ReplyDelete