Using C# SortedList: Practical Examples

In C#, a SortedList is a collection of key/value pairs that are sorted according to the key. By default, this collection is sorted in ascending order for key/value pairs. It has a collection of generic and non-generic types. The generic SortedList is defined in the System.Collections.Generic namespace, while the non-generic SortedList is defined in the System Collections namespace below, and here we will discuss the non-generic type of SortedList.

Important Notes:

  • The SortedList class implements IEnumerable, ICollection, dictionaries, and cloning interfaces.
  • In the SortedList, elements can be accessed by their key or index.
  • The SortedList object internally maintains two arrays to store the elements of the list, i.e., one array for keys and the other for associated values.
  • Here, the key cannot be null, but the value can be null.
  • The capacity of the SortedList object is the number of key/value pairs it can hold.
  • In the SortedList, duplicate keys are not allowed.
  • In SortedList, you can store values of the same type and of different types due to non-generic collections. If you use a generic SortedList in your program, the values must be of the same type.
  • In a SortedList, you can’t store keys of different data types in the same SortedList, because the compiler will throw an exception. Therefore, always add the key to the SortedList of the same type.
  • You can also convert the key/value pair of a SortedList to a DictionaryEntry.

How do I create a SortedList?

The SortedList class provides 6 different types of constructors for creating a SortedList, here we will only use the SortedList() constructor. To learn more about the constructor of SortedList, see C#| SortedList class.

SortedList(): This is used to create an instance of the SortedList class, which is empty, has a default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.

Step 1: With the help of the using keyword, include the System.Collections namespace in the program:

using System.Collections;

Step 2: Create a SortedList using the SortedList class, as follows:

SortedList list_name = new SortedList();

Step 3: If you want to add a key/value pair to the SortedList, use the Add() method to add the key/value pair to your SortedList. Also, you can store key/value pairs in a SortedList without using the Add() method, which is called collection initialization syntax, as shown in the following example.

Step 4: Use the following command to access the key/value pairs of the SortedList in three different ways:

for loop:

You can use for to iterate over the key/value pair of the SortedList.

Example:

for ( int x = 0; x <my_slist1.Count; x++)
{
     Console.WriteLine( "{0} and {1}" , my_slist1.GetKey(x), my_slist1.GetByIndex(x));
}

Using Indexes:

You can use the index to access the individual values of the SortedList. You’ll need to pass the key or index as a parameter to find the corresponding value. If the specified key is not available, the compiler throws an error.

Example:

Console.WriteLine( "Value is:{0}" , my_slist1[1.04]);
  
string x = ( string )my_slist[1.02];
  
Console.WriteLine(x);

foreach loop:

You can use the foreach loop to access the key/value pair of the SortedList.

Example:

foreach (DictionaryEntry pair in my_slist1)
{
     Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
}

Example:

//C# program to illustrate how
//to create a sortedlist
using System;
using System.Collections;
  
class GFG {
  
     //Main Method
     static public void Main()
     {
  
         //Creating a sortedlist
         //Using SortedList class
         SortedList my_slist1 = new SortedList();
  
         //Adding key/value pairs in 
         //SortedList using Add() method
         my_slist1.Add(1.02, "This" );
         my_slist1.Add(1.07, "Is" );
         my_slist1.Add(1.04, "SortedList" );
         my_slist1.Add(1.01, "Tutorial" );
  
         foreach (DictionaryEntry pair in my_slist1)
         {
             Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
         }
         Console.WriteLine();
  
         //Creating another SortedList
         //using Object Initializer Syntax
         //to initalize sortedlist
         SortedList my_slist2 = new SortedList() {
                                   { "b.09" , 234 }, { "b.11" , 395 }, { "b.01" , 405 }, { "b.67" , 100 }};
                  
         foreach (DictionaryEntry pair in my_slist2)
         {
             Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
         }
     }
}

The output is as follows:

1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

b.01 and 405
b.09 and 234
b.11 and 395
b.67 and 100

How do I remove an element from a SortedList?

  • Explicit: This method is used to remove all elements from the SortedList object.
  • Remove: This method is used to remove an element with the specified key from the SortedList object.
  • RemoveAt: This method is used to delete the element at the specified index of the SortedList object.

Example:

//C# program to illustrate how to
//remove key/value pairs from 
//the sortedlist
using System;
using System.Collections;
  
class GFG {
  
     //Main Method
     static public void Main()
     {
  
         //Creating a sortedlist
         //Using SortedList class
         SortedList my_slist = new SortedList();
  
         //Adding key/value pairs in SortedList
         //Using Add() method
         my_slist.Add(1.02, "This" );
         my_slist.Add(1.07, "Is" );
         my_slist.Add(1.04, "SortedList" );
         my_slist.Add(1.01, "Tutorial" );
  
         foreach (DictionaryEntry pair in my_slist)
         {
             Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
         }
         Console.WriteLine();
  
         //Remove value having 1.07 key
         //Using Remove() method
         my_slist.Remove(1.07);
  
         //After Remove() method
         foreach (DictionaryEntry pair in my_slist)
         {
             Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
         }
         Console.WriteLine();
  
         //Remove element at index 2
         //Using RemoveAt() method
         my_slist.RemoveAt(2);
  
         //After RemoveAt() method
         foreach (DictionaryEntry pair in my_slist)
         {
             Console.WriteLine( "{0} and {1}" , pair.Key, pair.Value);
         }
         Console.WriteLine();
  
         //Remove all key/value pairs
         //Using Clear method
         my_slist.Clear();
         Console.WriteLine( "The total number of key/value pairs" +
                     " present in my_slist:{0}" , my_slist.Count);
     }
}

The output is as follows:

1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

1.01 and Tutorial
1.02 and This
1.04 and SortedList

1.01 and Tutorial
1.02 and This

The total number of key/value pairs present in my_slist:0

How do I check the availability of key/value pairs in SortedList?

In the SortedList, you can check if a given pair exists using the following method:

  • Contains: This method is used to check if the SortedList object contains a specific key.
  • ContainsKey: This method is used to check if the SortedList object contains a specific key.
  • Include Value: This method is used to check if the SortedList object contains a specific value.

Example:

//C# program to illustrate how to
//check the given key or value 
//present in the sortedlist or not
using System;
using System.Collections;
  
class GFG {
  
     //Main Method
     static public void Main()
     {
  
         //Creating a sortedlist
         //Using SortedList class
         SortedList my_slist = new SortedList();
  
         //Adding key/value pairs in 
         //SortedList using Add() method
         my_slist.Add(1.02, "This" );
         my_slist.Add(1.07, "Is" );
         my_slist.Add(1.04, "SortedList" );
         my_slist.Add(1.01, "Tutorial" );
  
         //Using Contains() method to check
         //the specified key is present or not
         if (my_slist.Contains(1.02) == true ) 
         {
             Console.WriteLine( "Key is found...!!" );
         }
  
         else 
         {
             Console.WriteLine( "Key is not found...!!" );
         }
  
         //Using ContainsKey() method to check
         //the specified key is present or not
         if (my_slist.ContainsKey(1.03) == true ) 
         {
             Console.WriteLine( "Key is found...!!" );
         }
         else
         {
             Console.WriteLine( "Key is not found...!!" );
         }
  
         //Using ContainsValue() method to check
         //the specified value is present or not
         if (my_slist.ContainsValue( "Is" ) == true ) 
         {
             Console.WriteLine( "Value is found...!!" );
         }
  
         else 
         {
             Console.WriteLine( "Value is not found...!!" );
         }
     }
}

The output is as follows:

Key is found...!!
Key is not found...!!
Value is found...!!