SortedList.SetByIndex Method (Int32, Object)


Replaces the value at a specific index in a SortedList object.

Namespace:   System.Collections
Assembly:  mscorlib (in mscorlib.dll)

Public Overridable Sub SetByIndex (
	index As Integer,
	value As Object


Type: System.Int32

The zero-based index at which to save value.

Type: System.Object

The Object to save into the SortedList object. The value can be null.

Exception Condition

index is outside the range of valid indexes for the SortedList object.

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 object.

This method is an O(1) operation.

The following code example shows how to replace the value of an existing element in a SortedList object.

Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesSortedList    

    Public Shared Sub Main()

        ' Creates and initializes a new SortedList.
        Dim mySL As New SortedList()
        mySL.Add(2, "two")
        mySL.Add(3, "three")
        mySL.Add(1, "one")
        mySL.Add(0, "zero")
        mySL.Add(4, "four")

        ' Displays the values of the SortedList.
        Console.WriteLine("The SortedList contains the following" & _

        ' Replaces the values at index 3 and index 4.
        mySL.SetByIndex(3, "III")
        mySL.SetByIndex(4, "IV")

        ' Displays the updated values of the SortedList.
        Console.WriteLine("After replacing the value at index 3 and index 4,")
    End Sub 'Main

    Public Shared Sub PrintIndexAndKeysAndValues(myList As SortedList)
        Console.WriteLine(ControlChars.Tab & "-INDEX-" & ControlChars.Tab & _
           "-KEY-" & ControlChars.Tab & "-VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine(ControlChars.Tab & "[{0}]:" & ControlChars.Tab & _
               "{1}" & ControlChars.Tab & "{2}", i, myList.GetKey(i), _
        Next i
    End Sub
End Class

' This 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
' After replacing the value at index 3 and index 4,
'     -INDEX-    -KEY-    -VALUE-
'     [0]:    0    zero
'     [1]:    1    one
'     [2]:    2    two
'     [3]:    3    III
'     [4]:    4    IV

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top