SortedList
Some collections keep their element sorted as you use them. The SortedList
type, for example, always sorts its keys. We add keys and values to SortedList
.
Unlike a List
, the SortedList
stores both keys and values. For a collection with just keys (that is more like a List
, except no duplicates) consider a SortedSet
.
Here we create a SortedList
, and then invoke Add()
. In Add, the first argument is the key to add. The second argument is the value at that key.
For-Each
loop over the SortedList
. The KeyValuePair
is used (with matching types to the SortedList
) in the loop.SortedList
has no ways to reorder its elements. If you want to change the ordering, you must create a new collection.Module Module1 Sub Main() ' Create SortedList and add Strings to it. Dim sorted As SortedList(Of String, String) = New SortedList(Of String, String) sorted.Add("dog", "red") sorted.Add("cat", "black") sorted.Add("zebra", "black and white") sorted.Add("ant", "black") ' Loop over pairs in the collection. For Each pair As KeyValuePair(Of String, String) In sorted Console.WriteLine(pair.Key + "/" + pair.Value) Next End Sub End Moduleant/black cat/black dog/red zebra/black and white
IndexOfKey
We can search for keys and values in the SortedList
. To find a key, use IndexOfKey
. The special value -1 is returned if the key does not exist—no exception is thrown.
IndexOfValue
to find a value in the SortedList
. The special value -1 is used here too to mean "missing."Module Module1 Sub Main() Dim items = New SortedList(Of String, Integer) items.Add("bird", 20) items.Add("fish", 0) ' Display all pairs. For Each item As KeyValuePair(Of String, Integer) In items Console.WriteLine("ITEM: {0}", item) Next ' Find this key. Dim indexFish = items.IndexOfKey("fish") Console.WriteLine("INDEX OF FISH: {0}", indexFish) ' Find this value. Dim index20 = items.IndexOfValue(20) Console.WriteLine("INDEX OF 20: {0}", index20) ' If a key or value is missing, the value -1 is returned. Dim indexMissing = items.IndexOfKey("carrot") Console.WriteLine("INDEX OF CARROT: {0}", indexMissing) End Sub End ModuleITEM: [bird, 20] ITEM: [fish, 0] INDEX OF FISH: 1 INDEX OF 20: 0 INDEX OF CARROT: -1
If we try to add a duplicate to the SortedList
, an exception is thrown. We cannot call Add without first checking for the key in the List
(consider IndexOfKey
).
The SortedList
is a sorted list of pairs. It is not used in the same way as a List
, which makes it harder to apply in programs. A SortedSet
is often a better choice.