C# | Replacing the value at a specific index in a SortedList object
SortedList.SetByIndex(Int32, Object) Method is used to replace the value at a specific index in a SortedList object.
public virtual void SetByIndex (int index, object value);
index: It is the zero-based index at which to save value.
value: It is the Object to save into the SortedList object. The value can be null.
Exception: This method throws ArgumentOutOfRangeException if the index is outside the range of the valid indexes of the given SortedList Object.
Below programs illustrate the use of above-discussed method:
----- Before Replacing ----- Index Keys Values  Fifth Manish  First Ram  Fourth Rohit  Second Shyam  Third Mohit ----- After Replacing ----- Index Keys Values  Fifth Manish  First Priyanka  Fourth Rohit  Second Ritu  Third Mohit
Example 2: Demonstrating the case where ArgumentOutOfRangeException can occur
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
- 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 after adding and removing the elements from the SortedList object.
- This method is an O(1) operation.