SortedList: IndexOfKey |
Returns the zero-based index of the specified key in a SortedList object.
Public Function IndexOfKey( ByRef Key As Variant ) As Long
The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created, or the default Comparer.
The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList.
This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count.
Exception | Condition |
---|---|
InvalidOperationException | The comparer throws an exception. |
The following code example shows how to determine the index of a key or a value in a SortedList object.
Public Sub Main() Dim List As New SortedList Dim Key As Integer Dim Value As String List.Add 1, "one" List.Add 3, "three" List.Add 2, "two" List.Add 4, "four" List.Add 0, "zero" Debug.Print "The SortedList contains the following values:" PrintIndexAndKeysAndValues List Key = 2 Debug.Print CorString.Format("The key ""{0}"" is at index {1}.", Key, List.IndexOfKey(Key)) Value = "three" Debug.Print CorString.Format("The value ""{0}"" is at index {1}.", Value, List.IndexOfValue(Value)) End Sub Private Sub PrintIndexAndKeysAndValues(ByVal List As SortedList) Dim i As Long Debug.Print t("-INDEX-\t-KEY-\t-VALUE-") For i = 0 To List.Count - 1 Debug.Print CorString.Format(t("[{0}]:\t{1}\t{2}"), i, List.GetKey(i), List.GetByIndex(i)) Next Debug.Print End Sub ' The following code produces the following output. ' ' The SortedList contains the following values: ' -INDEX- -KEY- -VALUE- ' [0]: 0 zero ' [1]: 1 one ' [2]: 2 two ' [3]: 3 three ' [4]: 4 four ' ' The key "2" is at index 2. ' The value "three" is at index 3.