12

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

Thank you.

Eugene
  • 2,965
  • 2
  • 34
  • 39

5 Answers5

34

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));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
16

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

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());
j0tt
  • 1,108
  • 1
  • 7
  • 16
2

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);
nightcoder
  • 13,149
  • 16
  • 64
  • 72
0
List<T>.Sort(YourDateTimeComparer) where YourDateTimeComparer : IComparer<DateTime>

Here is an example of custom IComparer use: How to remove duplicates from int[][]

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433