C# - SortedList.IndexOfKey() Method with Example

In this tutorial, we will learn about the C# SortedList.IndexOfKey() method with its definition, usage, syntax, and example. By Nidhi Last updated : March 31, 2023

SortedList.IndexOfKey() Method

The SortedList.IndexOfKey() is used to get the zero-based index of the specified key in a SortedList.


int SortedList.IndexOfKey(object key);


  • 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.

C# Example of SortedList.IndexOfKey() Method

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);



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 »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.