C# Sort Array List
Tuesday 30th October 2007 at 16:46

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.

+
0 Comments   |   Permalink   |
Add your own comment

Use the form below to add a new comment to the blog entry and other comments above.

Visitor Name:
Visitor Comment:
Email Address:

Your email address will NOT be forwarded to any third parties.

 
Visual CAPTCHA
Captcha Image: