M Harvey wrote:
I have an arraylist that contains datetime values. What is the best way
to sort this arraylist by date ascending?
ArrayList has a Sort method which should sort them correctly. If you
need to sort them in a descending order or if there is more data than
just the DateTime, you will have to create a class that implements
IComparer. That class would have a single Compare method which you
would implement to compare 2 of your specific objects.
Here is a simple implementation that uses DateTime objects. It uses
the generic IComparer class so it requires v2.0 of the framework for
v1.1, you would code it the same way except using the IComparer class:
class DateTimeComparer : IComparer<DateTime>
{
private bool _sortDescending = false;
//pass true to the constructor to sort descending
public DateTimeComparer(bool descending)
{
_sortDescending = descending;
}
public int Compare(DateTime x, DateTime y)
{
if (_sortDescending)
return y.CompareTo(x);
else
return x.CompareTo(y);
}
}
And you would call the code like this:
//sort ascending
MyArrayList.Sort(new DateTimeComparer(false));
or
//sort descending
MyArrayList.Sort(new DateTimeComparer(true));
NOTE You don't need this class if your arraylist only contains
DateTime instances because DateTime implements IComparable and the the
ArrayList.Sort method will be able to sort them directly. I just
showed this class to show how easy the IComparer interface is.