Related Articles

Related Articles

C# | Getting the key at the specified index of a SortedList object
  • Last Updated : 01 Feb, 2019

SortedList.GetKey(Int32) Method is used to get the key at the specified index of a SortedList object.

Syntax:

public virtual object GetKey (int index);

Here, index is the zero-based index of the key to get.

Return Value: This method returns the key at the specified index of the SortedList object.

Exception: This method throws ArgumentOutOfRangeException if the index is outside the range of valid indexes for the SortedList object.



Below programs illustrate the use of above-discussed method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get the key at
// the specified index of a
// SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("key1", "C++");
        mylist.Add("key2", "Java");
        mylist.Add("key3", "DSA");
        mylist.Add("key4", "Python");
        mylist.Add("key5", "C#");
  
        // storing the value of
        // index that needed by
        // used into a variable
        int i = 2;
  
        // getting the key at index 2
        Console.WriteLine("Key at index {0} is {1}",
                          i, mylist.GetKey(i));
    }
}

chevron_right


Output:

Key at index 2 is key3

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get the key at
// the specified index of a
// SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("First", "Ram");
        mylist.Add("Second", "Shyam");
        mylist.Add("Third", "Mohit");
        mylist.Add("Fourth", "Rohit");
        mylist.Add("Fifth", "Manish");
  
        // storing the value of
        // index that needed by
        // used into a variable
        // it will throw an exception
        // as index is out of range of 
        // valid indexes of SortedList object
        int i = 7;
  
        // getting the key at index 7
        Console.WriteLine("Key at index {0} is {1}",
                          i, mylist.GetKey(i));
    }
}

chevron_right


Runtime Error:

Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Reference:




My Personal Notes arrow_drop_up
Recommended Articles
Page :