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:
using System;
using System.Collections;
class Geeks {
public static void Main(String[] args)
{
SortedList mylist = new SortedList();
mylist.Add( "key1" , "C++" );
mylist.Add( "key2" , "Java" );
mylist.Add( "key3" , "DSA" );
mylist.Add( "key4" , "Python" );
mylist.Add( "key5" , "C#" );
int i = 2;
Console.WriteLine( "Key at index {0} is {1}" ,
i, mylist.GetKey(i));
}
}
|
Output:
Key at index 2 is key3
Example 2:
using System;
using System.Collections;
class Geeks {
public static void Main(String[] args)
{
SortedList mylist = new SortedList();
mylist.Add( "First" , "Ram" );
mylist.Add( "Second" , "Shyam" );
mylist.Add( "Third" , "Mohit" );
mylist.Add( "Fourth" , "Rohit" );
mylist.Add( "Fifth" , "Manish" );
int i = 7;
Console.WriteLine( "Key at index {0} is {1}" ,
i, mylist.GetKey(i));
}
}
|
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: