65.9K
CodeProject is changing. Read more.
Home

Sorting custom type elements stored in an ArrayList

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.56/5 (36 votes)

Feb 12, 2005

1 min read

viewsIcon

74117

downloadIcon

696

Sorting custom type elements stored in an ArrayList.

Introduction

Many times we find ourselves in a situation where we need to sort custom type elements stored in an ArrayList according to some property of the element. In fact, I could not find anybody to help me with this problem, and that's why I decided to deal with this problem - and shared the solution I found with others here on CodeProject.

Solving the problem

Suppose we have some structure with only an integer and a string property which will be used in the sort operation later. For the sake of simplicity let's suppose we have the following structure:

public struct MyStrcuture
{
   public Int32 iID;
   public String sName;
}

In order to be able to sort custom type elements contained in an ArrayList, we have to define the CompareTo method of the IComparable interface for the element, and then use the ArrayList's .Sort() method. This -of course- means that our structure should be inherited from that interface .. and so we'll do!

public struct MyStrcuture : IComparable
{
   public Int32 iID;
   public String sName;

   public Int32 CompareTo(Object obj) 
   {
      MyStrcuture tmpObj = (MyStrcuture) obj;
      return (this.sName.CompareTo(tmpObj.sName));
   }
}

As you see, it is in the structure where we define the .CompareTo() method and you as a developer could write any code that suits your needs.

After this we need to test all this, let's suppose we fill an ArrayList with elements of MyStructure type:

ArrayList arlElements = new ArrayList();
for (Int32 iCounter = 1; iCounter <= 20; iCounter++)
{
   // Preparing element
   MyStructure myData = new MyStructure();
   myData.iID = iCounter;
   myData.sName = iCounter.ToString();

   //Adding element
   arlElements.Add(myData);
}

In order to sort, we only need to call the .Sort() method :-): arlElements.Sort();.

Hope this was useful. In the demo program you can find a workable version of the program with slight changes that do not alter its main concept.