Reputation: 13
apologies if the question is worded awkwardly, I really don't know a better way to explain what I need.
I have a list of dates and a list of activities that happened on those dates like so:
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
so on 06/01/2015 Kayaking was the selected activity and so on.
What I want to know is is there a way to reorder both the lists, preferably without using a loop and increment, so that they are in chronological order with this being the end result:
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
is there a way to do this in vb .net using visual express 2013? Thank you in advance -Tom
Upvotes: 0
Views: 1688
Reputation: 38875
It is hard to tell if what is shown is actually a List(Of T)
or an array. The listing seems seems more like a data display since it otherwise has syntax problems. Arrays are assumed.
If the LastDate and Activity are closely related, it is better to keep them together in a class rather than storing individual bits of data in their own container and dissociated from each other. For that, a class:
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
Then a (real) List to store them:
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#))
Lists are much easier to manage than arrays because you do not have to resize them or know how big to make them in advance. To sort the list by date, use the OrderBy
extension :
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
Results:
act: Rock Climbing last date: 1/1/2011
act: Bicycling last date: 6/1/2014
act: Kayaking last date: 4/1/2015
act: Cat Herding last date: 6/1/2015
Upvotes: 1
Reputation: 101092
The easiest way is to combine the two lists into one; then you can sort by the dates:
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))
Upvotes: 0