Home »
.Net »
C# Programs
C# program to get the index of the specified key in a SortedList (Example of IndexOfKey() Method)
C# SortedList.IndexOfKey() Method: Here, we are going to learn how to get the index of the specified key in a SortedList in C#.Net?
Submitted by Nidhi, on April 26, 2021
The IndexOfKey() method of SortedList class is used to get the zero-based index of the specified key in a SortedList.
Syntax:
int SortedList.IndexOfKey(object key);
Parameter(s):
- key: The key whose index to be found.
Return value:
It returns a zero-based index of the given key object, if the given key object is not found in the SortedList object it returns -1.
Program:
The source code to get the index of the specified key in a SortedList 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();
int index = 0;
//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("Index of keys:");
foreach (int key in list.GetKeyList())
{
index = list.IndexOfKey(key);
Console.WriteLine("Key "+key+" at index: "+index);
}
}
}
Output:
Index of keys:
Key 101 at index: 0
Key 102 at index: 1
Key 103 at index: 2
Key 104 at index: 3
Key 105 at index: 4
Press any key to continue . . .
C# SortedList Class Programs »