SortedList::SetByIndex Method (Int32, Object^)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

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

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

virtual void SetByIndex(
	int index,
	Object^ value


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.

#using <system.dll>

using namespace System;
using namespace System::Collections;
void PrintIndexAndKeysAndValues( SortedList^ myList )
   Console::WriteLine( "\t-INDEX-\t-KEY-\t-VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
      Console::WriteLine( "\t[{0}]:\t{1}\t{2}", i, myList->GetKey( i ), myList->GetByIndex( i ) );


int main()

   // Creates and initializes a new SortedList.
   SortedList^ mySL = gcnew 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 values:" );
   PrintIndexAndKeysAndValues( mySL );

   // 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," );
   PrintIndexAndKeysAndValues( mySL );

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