Sort List<DateTime> Descending

C#SortingLambda

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

Though it's untested...

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

should be the opposite of what you originally had.

Solution 2 - C#

What's wrong with:

docs.OrderByDescending(d => d.StoredDate);

Solution 3 - C#

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

Should do what you're looking for.

Solution 4 - C#

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

Note the minus sign.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris ConwayView Question on Stackoverflow
Solution 1 - C#Austin SalonenView Answer on Stackoverflow
Solution 2 - C#Scott BakerView Answer on Stackoverflow
Solution 3 - C#jonniiView Answer on Stackoverflow
Solution 4 - C#Tamas CzinegeView Answer on Stackoverflow