What is the SortedList class in C#?


A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

Let us see an example wherein we added 4 key and value pair for SortedList −

Example

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         SortedList s = new SortedList();

         s.Add("S1", "Maths");
         s.Add("S2", "Science");
         s.Add("S3", "English");
         s.Add("S4", "Economics");
      }
   }
}

Let us now see how to get the keys of a SortedList and display it −

Example

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

Updated on: 21-Jun-2020

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements