articles

Home / DeveloperSection / Articles / SortedList in C#

SortedList in C#

Anupam Mishra4468 01-Jan-2016

SortedList internally maintain two arrays to store the elements of the list, i.e. one array maintain a keys and another one storing associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. In SortedList a key cannot be null, but a value can be. A SortedList elements can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation.

The capacity of SortedList object is depends upon its element but by default capacity is 16. When elements are added to the SortedList, the capacity is automatically increased as required through reallocation. You can decrease the capacity of your SortedList by calling TrimToSize or by setting the Capacity property explicitly.

The index sequence is based on the sort sequence. When an element is added to SortedList, It is set correct sort order and the indexing adjust accordingly. Therefore, the index of a specific key/value pair in SortedList might change as elements are added or removed from the SortedList object.

In SortedList objects tends to be slower than operations on a Hashtable because of sorting.

However, the SortedList offer more flexibility by allowing access to the variables either through the associated keys or through the indexes.

Creating a SortedList:
SortedList sl = new SortedList(); 
// Adding elements in the SortedList
            sl.Add("1", "One");
            sl.Add("10", "Ten");
            sl.Add("3", "Three");

//Retrieving elements to the SortedList
            ICollection key = sl.Keys;
            foreach (var n in key)
            {
                Console.WriteLine(n+": "+sl[n]);
            }
 
Output:
       1: One
      10: Ten
       3: Three

 
For checking the capacity of SortedList use Capacity properties i.e. follows:
  Console.WriteLine (“Counts number of elements:  {0}”, sl.Count);
//For checking capacity you can use sl.Capacity property.
        // Fethching values by index
            Console.WriteLine("{0}", sl.GetByIndex(1));
   
    // Fethching key by index
           Console.WriteLine("{0}", sl.GetKey(1));

 Advantage:

1. It boots performance for lookups because its uses internally binary search algorithm.

2.     It may requires low memory for storage.

3.     It performs well on small data sets. 

For example,we create an instance of SortedList and adding three elements in it. Then we are retrieving all elements in the SortedList and performs various operations using its methods. 

using System;
using System.Collections;
namespace SortedListEx
{
    classProgram
    {
        staticvoid Main(string[] args)
        {
            //Creating SortedList
            SortedList sl = newSortedList();
            sl.Add("1", "One");
            sl.Add("10", "Ten");
            sl.Add("3", "Three");
            // Fethching all elements
            ICollection key = sl.Keys;
            Console.WriteLine("Retrieving all elements in the SortedList:");
            Console.WriteLine();
            foreach (var n in key)
            {
                Console.WriteLine(n+":"+sl[n]);
            }
            Console.WriteLine();
            if (sl.ContainsValue("Two"))
            {
                Console.WriteLine("Two is already exists");
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("Adding 'Two' in sorted List");
                sl.Add("2", "Two");
            }
            Console.WriteLine();
            Console.WriteLine("Number of Elemnts: "+sl.Count);
            Console.WriteLine();
            Console.WriteLine("Capacity: " + sl.Capacity);
            Console.WriteLine();
            int k = 1;
            Console.WriteLine("Fetching values passing index {0}", sl.GetByIndex(k));
            Console.WriteLine();
            // Fethching Key by passing index
            Console.WriteLine("Fetching Key by passing index: {0}" , sl.GetKey(k));
            Console.ReadLine();
        }
    }
}
 Output:

SortedList in C#


Updated 28-Oct-2019

Leave Comment

Comments

Liked By