SortedList.IndexOfKey(Object) Method is used to get the zero-based index of the specified key in a SortedList object.
public virtual int IndexOfKey (object key);
Here, key is the Key which is to be located in the SortedList object.
Return Value: This method returns the zero-based index of type
System.Int32 of the key parameter if the key is found in the SortedList object otherwise it returns -1.
- ArgumentNullException: If the key is null.
- InvalidOperationException: If the comparer throws an exception.
Below programs illustrate the use of above-discussed method:
Index Keys Values  Fifth Manish  First Ram  Fourth Rohit  Second Shyam  Third Mohit The index of key 'Third' is: 4 The index of key 'Sixth' is: -1
Example 2: To demonstrate the case where
ArgumentNullException can occur
System.ArgumentNullException: Key cannot be null.
Parameter name: key
- 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. So, the index of a specific key/value pair may change.
- This method uses a binary search algorithm so, this method is an O(log n) operation, where n is the Count.