There is no native way to sort a Microsoft.VisualBasic.Collection. I suggest converting to a newer type such as List(Of T)
.
Anyway, here is an example of converting a Collection
to a List(Of T)
Define the class which holds your events. You didn't provide it. I'll guess
Class myEvent
Public Property Name As String
Public Property CurDate As DateTime
Public Property EventDate As DateTime
End Class
Now make a few events and add them to the collection. I'm adding them out of order
Dim colEvents As New Collection()
Dim objList1 As New myEvent()
objList1.Name = "Name1"
objList1.EventDate = New DateTime(2016, 12, 20)
objList1.CurDate = DateTime.Now
colEvents.Add(objList1)
Dim objList2 As New myEvent()
objList2.Name = "Name2"
objList2.EventDate = New DateTime(2016, 12, 5)
objList2.CurDate = DateTime.Now
colEvents.Add(objList2)
Dim objList3 As New myEvent()
objList3.Name = "Name3"
objList3.EventDate = New DateTime(2016, 12, 10)
objList3.CurDate = DateTime.Now
colEvents.Add(objList3)
Here is where it can be converted to a List(Of myEvent)
, and sorted at the same time. Oh, since it's not a primitive type, you must supply a function to OrderBy
so it knows how to sort. This function simply returns the EventDate
Dim eventsList As New List(Of myEvent)(
colEvents.
OfType(Of myEvent).
OrderBy(Function(l As myEvent) l.EventDate))
Just to confirm the order, print the contents of both objects
Console.WriteLine("Collection:")
For Each c As myEvent In colEvents
Console.WriteLine(
String.Format("Name: {0}, Event date: {1}",
c.Name, c.EventDate))
Next
Console.WriteLine("List:")
For Each l In eventsList
Console.WriteLine(
String.Format("Name: {0}, Event date: {1}",
l.Name, l.EventDate))
Next
Output:
Collection:
Name: Name1, Event date: 12/20/2016 12:00:00 AM
Name: Name2, Event date: 12/5/2016 12:00:00 AM
Name: Name3, Event date: 12/10/2016 12:00:00 AM
List:
Name: Name2, Event date: 12/5/2016 12:00:00 AM
Name: Name1, Event date: 12/10/2016 12:00:00 AM
Name: Name3, Event date: 12/20/2016 12:00:00 AM
I interpreted your statement I want to check if EventDate <= CurDate, then sort the data in the collection such that past and current dates are arranged at the top, and future dates come after past and current dates, to simply mean that you want to sort in ascending order, and that CurDate
doesn't serve any purpose. If this is wrong then please clarify and we can fix the OrderBy
lambda in my example.
And if you are really stuck with Collection
, see this similar question related to sorting VBA collections