C# - SortedList.SetByIndex() Method with Example

In this tutorial, we will learn about the C# SortedList.SetByIndex() method with its definition, usage, syntax, and example. By Nidhi Last updated : March 31, 2023

SortedList.SetByIndex() Method

The SortedList.SetByIndex() method is used to set the value using the index. It replaces the existing value with a new value which is given in SetByIndex() method.

Syntax

void SortedList.SetByIndex(int index, object? value);

Parameter(s)

  • index: The index at which to set the value.
  • value: The value to set into the SortedList object, it can also be null.

Return Value

It does not return any value.

Exception(s)

  • System.ArgumentOutOfRangeException

C# Example of SortedList.SetByIndex() Method

The source code to replace the value at a specific index in a SortedList object is given below. The given program is compiled and executed successfully.

using System;
using System.Collections;

class SortedListEx {
  //Entry point of Program
  static public void Main() {
    //Creation of SortedList object
    SortedList list = new SortedList();

    //Add elements to SortedList 
    list.Add(101, "India    ");
    list.Add(105, "America  ");
    list.Add(102, "Austrelia");
    list.Add(103, "Africa   ");
    list.Add(104, "Canada   ");

    Console.WriteLine("Values before SetByIndex:");
    foreach(string value in list.Values) {
      Console.WriteLine("\t" + value);
    }

    list.SetByIndex(2, "DELHI");

    Console.WriteLine("Values after SetByIndex:");
    foreach(string value in list.Values) {
      Console.WriteLine("\t" + value);
    }
  }
}

Output

Values before SetByIndex:
        India
        Austrelia
        Africa
        Canada
        America
Values after SetByIndex:
        India
        Austrelia
        DELHI
        Canada
        America
Press any key to continue . . .

C# SortedList Class Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.