Sort the objects in ArrayList


It should be a frequent scenario to sort the order of objects in a collection, such as ArrayList. ArrayList in c# provide a method named Sort(). But we need to let ArrayList know the detailed sorting algorithm.


There are two means to implement this:


1. Make the target class inheritted from IComparable interface, and provide CompareTo() method. IComparable interface comes from System namespace.


For example:


    class UITestCase: IComparable
    {
        private int _sequenceno = 0;
        public int SequenceNo
        {
            get
            {
                return _sequenceno;
            }
            set
            {
                _sequenceno = value;
            }
        }
......


        // implement the IComparable interface, define the algorithm here
        public Int32 CompareTo(object next)
        {
            UITestCase nextCase = (UITestCase)next;


            return (this.SequenceNo.CompareTo(nextCase.SequenceNo));
        }
    } // class end.


When using ArrayList to store a group of UITestCase objects, we could simply call ArrayList.Sort() to sort all objects in it.


                // get all test case entities, then make sort order
                ArrayList caseList = new ArrayList();
                foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories("*.tc"))
                {
                    UITestCase testcase = new UITestCase(dir.FullName);


                    caseList.Add(testcase);
                }


                if (caseList.Count > 0)
                {
                    caseList.Sort();
                }


2. Create a class inherited from IComparer interface, then implement Compare(object x, object y) method just like IComparable's CompareTo(object next) method.


3. Write a special method to sort the order of a given ArrayList like what we will do in C language, I prefer this one because I think the codes writing in above two methods are not straightforward enough.

Skip to main content