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++)
{
MyStructure myData = new MyStructure();
myData.iID = iCounter;
myData.sName = iCounter.ToString();
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.
Professional Software Developer, currently working for HVB bank.
Programming experience includes: C#, ASP.NET, Delphi, PHP, VB.
Technologies: MS SQL Server 2005, Apache, IIS.
Certifications: MCAD, MCSD, MCTS (MS SQL Server 2005), MCITP