12

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

Thank you.

5 Answers 5

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));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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());

1 Comment

...and moderately more efficient (avoids the multiply per comparison).
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);

1 Comment

From ArrayList you'd need a Cast<DateTime>() in there too.
0
List<T>.Sort(YourDateTimeComparer) where YourDateTimeComparer : IComparer<DateTime>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.