How do I sort ArrayList of DateTime objects in descending order?
Thank you.
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); });
With lambda expressions in C# 3, the delegate is easier to create:
list.Sort((x, y) => y.CompareTo(x));
As "Guffa" already said, you shouldn't be using ArrayList
unless you are in .NET 1.1; here's a simpler List<DateTime>
example, though:
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
Your dates are now sorted in descending order.
Use a DateTime Comparer that sorts in reverse. Call Sort.
public class ReverseDateComparer:IComparer{
public int Compare(object x, object y){
return -1 * DateTime.Compare(x, y);
}
}
list.Sort(new ReverseDateComparer());
If you are using .NET 3.5:
// ArrayList dates = ...
var sortedDates = dates.OrderByDescending(x => x);
// test it
foreach(DateTime dateTime in sortedDates)
Console.WriteLine(dateTime);
List<T>.Sort(YourDateTimeComparer) where YourDateTimeComparer : IComparer<DateTime>
Here is an example of custom IComparer use: How to remove duplicates from int[][]