55

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.

4 Answers 4

91

Though it's untested...

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

should be the opposite of what you originally had.

2
  • Can you explain more about what is happening with the list and why ? Mar 28 at 19:42
  • 1
    OP was comparing x to y and then reversing; logically, this is the same as comparing y to x and leaving in that order. Apr 5 at 0:33
67

What's wrong with:

docs.OrderByDescending(d => d.StoredDate);
2
  • 7
    Note that this creates a new ordered list rather than modifying the list in place. Granted, the performance loss is negligible. Oct 19, 2012 at 15:01
  • 12
    Adding to what Cavyn said, this will always returns list of IOrderedEnumerable<T> which would need to be converted back to generic list using .ToList<T>().
    – digitguy
    Dec 11, 2012 at 10:12
22
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));

Should do what you're looking for.

1
  • Can you explain more about what is happening with the list and why ? Mar 28 at 19:43
8
docs.Sort((x, y) => -x.StoredDate.CompareTo(y.StoredDate));

Note the minus sign.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.