Sort List Descending

2019-02-01 16:43发布

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条回答
再贱就再见
2楼-- · 2019-02-01 16:49

Though it's untested...

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

should be the opposite of what you originally had.

查看更多
我只想做你的唯一
3楼-- · 2019-02-01 17:00
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));

Should do what you're looking for.

查看更多
地球回转人心会变
4楼-- · 2019-02-01 17:01
docs.Sort((x, y) => -x.StoredDate.CompareTo(y.StoredDate));

Note the minus sign.

查看更多
迷人小祖宗
5楼-- · 2019-02-01 17:04

What's wrong with:

docs.OrderByDescending(d => d.StoredDate);
查看更多
登录 后发表回答