What is the Keys property of SortedList class in C#?


Get the keys in the SortedList using the keys property of SortedList class in C#. We have first set the SortedList property with elements.

SortedList sl = new SortedList();
sl.Add("ST0", "One");
sl.Add("ST1", "Two");
sl.Add("ST2", "Three");
sl.Add("ST3", "Four");
sl.Add("ST4", "Five");
sl.Add("ST5", "Six");
sl.Add("ST6", "Seven");

Now use the keys property to get the keys.

ICollection key = sl.Keys;

The following is the complete code to implement keys property of SortedList class.

Example

 Live Demo

using System;
using System.Collections;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         SortedList sl = new SortedList();
         sl.Add("ST0", "One");
         sl.Add("ST1", "Two");
         sl.Add("ST2", "Three");
         sl.Add("ST3", "Four");
         sl.Add("ST4", "Five");
         sl.Add("ST5", "Six");
         sl.Add("ST6", "Seven");
         ICollection key = sl.Keys;
         foreach (string k in key) {
            Console.WriteLine(k);
         }
      }
   }
}

Output

ST0
ST1
ST2
ST3
ST4
ST5
ST6

Updated on: 23-Jun-2020

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements