【问题标题】:How to sort a list of dates and sort another list into the same order? vb .net如何对日期列表进行排序并将另一个列表排序为相同的顺序? VB.net
【发布时间】:2015-04-24 15:13:20
【问题描述】:

抱歉,如果问题措辞尴尬,我真的不知道更好的方式来解释我需要什么。

我有一个日期列表和在这些日期发生的活动列表,如下所示:

Datelist(0) = 06/01/2015   Activitylist(0) = Kayaking
Datelist(1) = 04/01/2015   Activitylist(1) = Rock Climbing
Datelist(2) = 01/01/2015   Activitylist(2) = Hiking
Datelist(3) = 05/01/2015   Activitylist(3) = Orienteering

所以在 2015 年 6 月 1 日,皮划艇是选定的活动等等。

我想知道的是有没有办法重新排序两个列表,最好不使用循环和增量,以便它们按时间顺序排列,这是最终结果:

Datelist(0) = 01/01/2015   Activitylist(0) = Hiking
Datelist(1) = 04/01/2015   Activitylist(1) = Rock Climbing
Datelist(2) = 05/01/2015   Activitylist(2) = Orienteering
Datelist(3) = 06/01/2015   Activitylist(3) = Kayaking

有没有办法在 vb .net 中使用 visual express 2013 做到这一点?提前谢谢你-汤姆

【问题讨论】:

  • 为什么不使用 2 个列表/数组而不是 2 个列表/数组,而使用一个类来使用 .Sort 将信息一起排序?

标签: .net vb.net list sorting


【解决方案1】:

很难判断显示的内容实际上是List(Of T) 还是数组。该列表看起来更像是一个数据显示,因为它在其他方面存在语法问题。假定为数组。

如果 LastDate 和 Activity 密切相关,最好将它们放在一个类中,而不是将各个数据位存储在各自的容器中并相互分离。为此,一个类:

Public Class Activity
    Public Property Name As String
    Public Property LastDate As DateTime
    Public Property Rating As Integer

    Public Sub New(n As String, dt As DateTime)
        Name = n
        LastDate = dt
        Rating = 1          ' some default
    End Sub

End Class

然后是一个(真实的)列表来存储它们:

actList = New List(Of Activity)

Dim act As Activity
act = New Activity("Kayaking", #4/1/2015#)
actList.Add(act)

' short form, no temp var:
actList.Add(New Activity("Cat Herding", #6/1/2015#))
actList.Add(New Activity("Rock Climbing", #1/1/2011#))
actList.Add(New Activity("Bicycling", #6/1/2014#))

列表比数组更容易管理,因为您不必预先调整它们的大小或知道它们的大小。要按日期对列表进行排序,请使用 OrderBy 扩展名:

actList = actList.OrderBy(Function(d) d.LastDate).ToList
' display result:
For Each a As Activity In actList
    Console.WriteLine("act: {0}  last date: {1}", a.Name, a.LastDate.ToShortDateString)
Next

结果:

行动:攀岩最后日期:2011 年 1 月 1 日
行为:骑自行车 最后日期:2014 年 6 月 1 日
行为:皮划艇 最后日期:2015 年 4 月 1 日
行为:猫放牧最后日期:2015 年 6 月 1 日

【讨论】:

    【解决方案2】:

    最简单的方法是将两个列表合二为一;然后你可以按日期排序:

    Dim datelist = { #06/01/2015#, #04/01/2015#, #01/01/2015#, #05/01/2015# }
    Dim activities = { "Kayaking", "Rock Climbing", "Hiking", "Orienteering" }
    
    Dim combined = datelist.Zip(activities, Function (ActivityDate, Activity) New With {ActivityDate, Activity}).ToList()
    
    combined.Sort(Function (a, b) a.ActivityDate.CompareTo(b.ActivityDate))
    

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多