Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort ArrayList of DateTime objects in descending order?

Tags:

c#

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

Thank you.

like image 951
Eugene Avatar asked May 09 '09 22:05

Eugene


People also ask

How do you arrange an ArrayList in descending order?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections. reverseOrder() as the parameter and returns a Collection sorted in the Descending Order.

How do you sort dates in ArrayList?

Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects. Now in the main method use Collections. sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.

How do you sort an array of objects in Java in descending order?

Sort Array in Descending OrderJava Collections class provides the reverseOrder() method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter.


2 Answers

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));
like image 145
Guffa Avatar answered Sep 29 '22 15:09

Guffa


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.

like image 38
Marc Gravell Avatar answered Sep 29 '22 16:09

Marc Gravell