I have a the need for key value pair that I wish to sort so I decided to use a SortedList instead of a HashTable.
I am adding the data in the order below to my SortedList which is the order I need it in
Key | Value -------------------------------- 1 '700-800' | List(Of Object) 2 '900-1000' | List(Of Object) 3 '1100-1200' | List(Of Object) 4 '1700-1800' | List(Of Object) 5 '1900-2000' | List(Of Object)
The key is a string and the value is a List of objects. The key is representing a time slot that has been concatenated from two integer values and delimited by ‘-‘. ‘700’ as a string was 0700 initially an integer.
e.g.
Dim key As String = slotTimeStart.ToString() & '-' & slotTimeEnd.ToString()
But once these key value pairs are added to the SortedList they appear in the order
3 '1100-1200' | List(Of Object) 4 '1700-1800' | List(Of Object) 5 '1900-2000' | List(Of Object) 1 '700-800' | List(Of Object) 2 '900-1000' | List(Of Object)
Unfortunately I recieve the times slots as two integer values which cannot be changed.
Is there any way to force a sort on a SortedList? or is this problem because of the way I am storing my key? Is there a better way to store it?
Create a
SortedList(Of String, List(Of Object))but pass in anIComparer(Of String)to the constructor, where the implementation will compare the keys according to the ordering you want.You’ll have to implement that yourself, but it shouldn’t be too hard – just split the string by ‘-‘, parse both sides with
Int32.Parseand react accordingly. You may even not need to worry about the part after the ‘-‘, if your key ranges are non-overlapping.EDIT: Here’s a demo. It only prints out the keys, but that’s enough to show they’re sorted as you want them.