日期时间数组排序(Date Time Array Sort)

我有一个数组,其中包含日期对象,我需要按照日期按升序或降序排序,即最新的一个(日期也可以包含时间戳)。

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).

最满意答案

具有自定义IComparer(Of T)委托的Array.Sort(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))

我已经对日期进行了排序。但是我有一个包含日期对象作为成员的对象的数组。那么我如何对包含日期对象的对象数组进行排序?

您可以再次使用自定义Sort委托(假设对象是类Person ):

Array.Sort(Of Person)(persons, Function(p1, p2) p2.BirthDate.CompareTo(p1.BirthDate))

但最可读的方式是使用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

如果需要查询中的List,请使用.ToList() ,如果需要array使用.ToArray() 。

Array.Sort(Of T) with a custom IComparer(Of T) delegate should work:

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 Sort delegate(assuming the object is a class Person):

Array.Sort(Of Person)(persons, Function(p1, p2) p2.BirthDate.CompareTo(p1.BirthDate))

But the most readable way is using 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 array use .ToArray().

更多推荐