Open In App

C# | Getting the list of keys of a SortedList object

SortedList.GetKeyList Method is used to get the list of keys in a SortedList object.

Syntax:



public virtual System.Collections.IList GetKeyList ();

Return Value: It returns an IList object containing the keys in the SortedList object.

Below programs illustrate the use of above-discussed method:



Example 1:




// C# code for getting the keys
// in a SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // 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#");
  
        // taking an IList and
        // using GetKeyList method
        IList klist = mylist.GetKeyList();
  
        // Prints the list of keys
        Console.WriteLine("Key List");
  
        for (int i = 0; i < mylist.Count; i++)
            Console.WriteLine(klist[i]);
    }
}

Output:

Key List
1
2
3
4
5

Example 2:




// C# code for getting the keys
// in a SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // 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");
  
        // taking an IList and
        // using GetKeyList method
        IList klist = mylist.GetKeyList();
  
        // Prints the list of keys
        Console.WriteLine("Key List");
  
        // will print the keys in sorted order
        for (int i = 0; i < mylist.Count; i++)
            Console.WriteLine(klist[i]);
    }
}

Output:

Key List
Fifth
First
Fourth
Second
Third

Note:

Reference:


Article Tags :
C#