C# | Getting the value at the specified index of a SortedList object
SortedList.GetByIndex(Int32) Method is used to get the value at the specified index of a SortedList object.
Syntax:
public virtual object GetByIndex (int index);
Here index is the zero-based index of the value to get.
Return Value: It returns the value at the specified index of the SortedList object.
Exception: This method will throw 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 value 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( "1" , "C++" ); mylist.Add( "2" , "Java" ); mylist.Add( "3" , "DSA" ); mylist.Add( "4" , "Python" ); mylist.Add( "5" , "C#" ); // getting the indexing and // store into a variable int i = 4; // getting the value at index 4 Console.WriteLine( "Value at index {0} is {1}" , i, mylist.GetByIndex(i)); } } |
Output:
Value at index 4 is C#
Example 2:
// C# code to get the value 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" ); // getting the indexing and // store into a variable // it will give error as // index is out of range int i = 7; // getting the value at index 7 Console.WriteLine( "Value at index {0} is {1}" , i, mylist.GetByIndex(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.getbyindex?view=netframework-4.7.2