C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For Each: We use the For-Each loop over the SortedList. The KeyValuePair is used (with matching types to the SortedList) in the loop.
For Each, ForKeyValuePairTip: The SortedList has no ways to reorder its elements. If you want to change the ordering, you must create a new collection.
VB.NET program that uses SortedList
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 Module
Output
ant/black
cat/black
dog/red
zebra/black and white
IndexOfValue: Use this function to find a value in the SortedList. The special value -1 is used here too to mean "missing."
VB.NET program that uses IndexOfKey, IndexOfValue
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 Module
Output
ITEM: [bird, 20]
ITEM: [fish, 0]
INDEX OF FISH: 1
INDEX OF 20: 0
INDEX OF CARROT: -1