C# | How to create a SortedList

SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace.

Properties of SortedList:

  • Internally the object of SortedList maintains two arrays. The first array is used to store the elements of the list i.e. keys and the second one is used to store the associated values.
  • A key cannot be null but value can be.
  • As SortedList used sorting which makes it slower in comparison to Hashtable.
  • The capacity of a SortedList can be dynamically increased through reallocation.
  • The keys in the SortedList cannot be duplicated but values can be.
  • The SortedList can be sorted according to the keys using the IComparer(Either in ascending or descending order).

Below programs illustrate how to create a SortedList:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate how
// to create a SortedList
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating object of SortedList
        // fslist is the SortedList object
        SortedList fslist = new SortedList();
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give 0 as no pairs are present
        Console.WriteLine(fslist.Count);
    }
}

chevron_right


Output:

0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate how
// to create a SortedList
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating object of SortedList
        // fslist is the SortedList object
        SortedList fslist = new SortedList();
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give 0 as no pairs are present
        Console.WriteLine(fslist.Count);
  
        // Adding key/value pairs in fslist
        fslist.Add("1", "GFG");
        fslist.Add("2", "Geeks");
        fslist.Add("3", "for");
        fslist.Add("4", "Geeks");
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give output 4
        Console.WriteLine(fslist.Count);
    }
}

chevron_right


Output:

0
4

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.