vb.net 日期时间数组排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15385420/
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
Date Time Array Sort
提问by B2Mobile
I have an array which has date objects which i need to sort in ascending or descending order as per date i.e latest one first(date can also contain timestamp).
我有一个包含日期对象的数组,我需要按日期按升序或降序排序,即最新的第一个(日期也可以包含时间戳)。
回答by Tim Schmelter
Array.Sort(Of T)with a custom IComparer(Of T)delegate should work:
Array.Sort(Of T)使用自定义IComparer(Of T)委托应该可以:
Dim dates = {Date.Now, Date.Now.AddDays(1), Date.Now.AddDays(2)}
Array.Sort(Of Date)(dates, Function(d1, d2) d2.CompareTo(d1))
I have sorted the date.But i have an array with objects which contains date object as a member.So how do i sort the array of objects which contain date object?
我已经对日期进行了排序。但是我有一个包含日期对象作为成员的对象的数组。那么如何对包含日期对象的对象数组进行排序?
You can again use the custom Sortdelegate(assuming the objectis a class Person):
您可以再次使用自定义Sort委托(假设对象是一个类Person):
Array.Sort(Of Person)(persons, Function(p1, p2) p2.BirthDate.CompareTo(p1.BirthDate))
But the most readable way is using Linq:
但最易读的方式是使用 Linq:
Dim orderedPersons = From p In persons
Order By p.BirthDate Descending
For Each p In orderedPersons
Console.WriteLine("{0}'s birtdate is at {1}", p.Name, p.BirthDate)
Next
If you need a List from the query use .ToList(), if you need an arrayuse .ToArray().
如果你需要一个来自查询的 List 使用.ToList(),如果你需要一个arrayuse .ToArray()。

