C# 排序 List<DateTime> 降序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/244219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort List<DateTime> Descending
提问by Chris Conway
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,
在 c#(3.0 或 3.5,所以我们可以使用 lambdas)中,是否有一种优雅的方式按降序对日期列表进行排序?我知道我可以做一个直接的排序然后扭转整个事情,
docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate));
docs.Reverse();
but is there a lambda expression to do it one step?
但是是否有一个 lambda 表达式可以一步到位?
In the above example, StoredDate is a property typed as a DateTime.
在上面的示例中,StoredDate 是一个类型为 DateTime 的属性。
采纳答案by Austin Salonen
Though it's untested...
虽然它未经测试...
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));
should be the opposite of what you originally had.
应该与您最初拥有的相反。
回答by jonnii
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));
Should do what you're looking for.
应该做你正在寻找的。
回答by Tamas Czinege
docs.Sort((x, y) => -x.StoredDate.CompareTo(y.StoredDate));
Note the minus sign.
注意减号。
回答by Scott Baker
What's wrong with:
有什么问题:
docs.OrderByDescending(d => d.StoredDate);