Open In App

C# | Getting the keys in a SortedList object

SortedList.Keys Property is used to get the keys in a SortedList object.

Syntax:



public virtual System.Collections.ICollection Keys { get; }

Property Value: An ICollection object containing the keys in the SortedList object.

Below programs illustrate the use of above-discussed property:



Example 1:




// C# code to get an ICollection containing
// the keys in the SortedList
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a SortedList
        SortedList mylist = new SortedList();
  
        // Adding elements in SortedList
        mylist.Add("4", "Even");
        mylist.Add("9", "Odd");
        mylist.Add("5", "Odd and Prime");
        mylist.Add("2", "Even and Prime");
  
        // Get a collection of the keys.
        ICollection c = mylist.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + mylist[str]);
    }
}

Output:
2: Even and Prime
4: Even
5: Odd and Prime
9: Odd

Example 2:




// C# code to get an ICollection containing
// the keys in the SortedList.
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a SortedList
        SortedList mylist = new SortedList();
  
        // Adding elements in SortedList
        mylist.Add("India", "Country");
        mylist.Add("Chandigarh", "City");
        mylist.Add("Mars", "Planet");
        mylist.Add("China", "Country");
  
        // Get a collection of the keys.
        ICollection c = mylist.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + mylist[str]);
    }
}

Output:
Chandigarh: City
China: Country
India: Country
Mars: Planet

Note:

Reference:


Article Tags :
C#