Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List<DateTime> Descending

Tags:

c#

sorting

lambda

In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing,

docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate)); docs.Reverse(); 

but is there a lambda expression to do it one step?

In the above example, StoredDate is a property typed as a DateTime.

like image 555
Chris Conway Avatar asked Oct 28 '08 18:10

Chris Conway


People also ask

How do I sort list of DateTime?

You only need to call a. sort() without assigning it to a again. There is a built in function sorted() , which returns a sorted version of the list - a = sorted(a) will do what you want as well.

How do you sort descending dates?

Here's how to sort unsorted dates: Drag down the column to select the dates you want to sort. Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

How do I sort a list by date in python?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.


2 Answers

Though it's untested...

docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate)); 

should be the opposite of what you originally had.

like image 82
Austin Salonen Avatar answered Sep 22 '22 21:09

Austin Salonen


What's wrong with:

docs.OrderByDescending(d => d.StoredDate); 
like image 29
Scott Baker Avatar answered Sep 22 '22 21:09

Scott Baker