C# | Getting the key at the specified index of a SortedList object
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:
// C# code to get the key at // the specified index of a // SortedList object using System; using System.Collections; class Beginner { // 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)); } } |
Output:
Key at index 2 is key3
Example 2:
// C# code to get the key at // the specified index of a // SortedList object using System; using System.Collections; class Beginner { // 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)); } } |
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:
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getkey?view=netframework-4.7.2