C# – How to sort ArrayList of DateTime objects in descending order

c

How do I sort ArrayList of DateTime objects in descending order?

Thank you.

Best Answer

First of all, unless you are stuck with using framework 1.1, you should not be using an ArrayList at all. You should use a strongly typed generic List<DateTime> instead.

For custom sorting there is an overload of the Sort method that takes a comparer. By reversing the regular comparison you get a sort in descending order:

list.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });

Update:

With lambda expressions in C# 3, the delegate is easier to create:

list.Sort((x, y) => y.CompareTo(x));