C# 如何按降序对DateTime对象的ArrayList进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/844251/
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
How to sort ArrayList of DateTime objects in descending order?
提问by Eugene
How do I sort ArrayList of DateTime objects in descending order?
如何按降序对 DateTime 对象的 ArrayList 进行排序?
Thank you.
谢谢你。
采纳答案by Guffa
First of all, unless you are stuck with using framework 1.1, you should not be using an ArrayList
at all. You should use a strongly typed generic List<DateTime>
instead.
首先,除非您坚持使用框架 1.1,否则您根本不应该使用 an ArrayList
。您应该改用强类型泛型List<DateTime>
。
For custom sorting there is an overload of the Sort
method that takes a comparer. By reversing the regular comparison you get a sort in descending order:
对于自定义排序,有一个Sort
采用比较器的方法的重载。通过反转常规比较,您可以按降序进行排序:
list.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });
Update:
更新:
With lambda expressions in C# 3, the delegate is easier to create:
使用 C# 3 中的 lambda 表达式,可以更轻松地创建委托:
list.Sort((x, y) => y.CompareTo(x));
回答by abatishchev
List<T>.Sort(YourDateTimeComparer) where YourDateTimeComparer : IComparer<DateTime>
Here is an example of custom IComparer use: How to remove duplicates from int[][]
这是自定义 IComparer 使用的示例:如何从 int[][] 中删除重复项
回答by j0tt
Use a DateTime Comparer that sorts in reverse. Call Sort.
使用反向排序的 DateTime 比较器。呼叫排序。
public class ReverseDateComparer:IComparer{
public int Compare(object x, object y){
return -1 * DateTime.Compare(x, y);
}
}
list.Sort(new ReverseDateComparer());
回答by nightcoder
If you are using .NET 3.5:
如果您使用的是 .NET 3.5:
// ArrayList dates = ...
var sortedDates = dates.OrderByDescending(x => x);
// test it
foreach(DateTime dateTime in sortedDates)
Console.WriteLine(dateTime);
回答by Marc Gravell
As "Guffa" already said, you shouldn't be using ArrayList
unless you are in .NET 1.1; here's a simpler List<DateTime>
example, though:
正如“Guffa”已经说过的,ArrayList
除非您在 .NET 1.1 中,否则不应使用;不过,这是一个更简单的List<DateTime>
例子:
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
Your dates are now sorted in descending order.
您的日期现在按降序排序。