
© deanpugh.com 2006, all rights reserved. Copyright Notice
Last Updated: Tuesday 15th September 2009 - 04:42
C# Sort Array List
During my first few days of learning C#, I needed to use an Array List to store a collection of objects.
I then needed to sort the Array List, but I couldn't seem to find a built in way to do this.
I searched the vast database that is the Internet and found the code below. It's a class that you need to add to your project, but will sort your Array List for you.
alStaffList.Sort(new PersonComparer());
public class PersonComparer : IComparer
{
private SortDirection m_direction = SortDirection.Ascending;
public PersonComparer() : base() { }
public PersonComparer(SortDirection direction)
{
this.m_direction = direction;
}
int IComparer.Compare(object x, object y)
{
BuffaloUtils.BuffaloUser personX = (BuffaloUtils.BuffaloUser) x;
BuffaloUtils.BuffaloUser personY = (BuffaloUtils.BuffaloUser) y;
if (personX == null &&personY == null)
{
return 0;
}
else if (personX == null && personY != null)
{
return (this.m_direction == SortDirection.Ascending) ? -1 : 1;
}
else if (personX != null && personY == null)
{
return (this.m_direction == SortDirection.Ascending) ? 1 : -1;
}
else
{
return (this.m_direction == SortDirection.Ascending) ?
personX.strFullName.CompareTo(personY.strFullName) :
personY.strFullName.CompareTo(personX.strFullName);
}
}
}
This code was taken from another project of mine. The BuffaloUtils.BuffaloUser is just a class which create an Staff Member object. You will need to replace this with what you are trying to compare.




