C# SortedList (SortedList<TKey,TValue>)

In c#, SortedList is a generic type of collection used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

 

By default, the sortedlist will sort key/value pairs in ascending order of the key, and the sortedlist will allow storing only the strongly-typed objects, i.e., the key/value pairs of the specified data type.

 

In c#, the sortedlist will allow us to store duplicate values, but the keys must be unique and cannot be null to identify the values in sortedlist. The size of sortedlist will vary dynamically so that you can add or remove elements from the sortedlist based on our application requirements.

C# SortedList Declaration

In c#, sortedlist is a generic type of collection, and it is provided by System.Collections.Generic namespace.

 

As discussed, the collection is a class, so to define a sortedlist, you need to declare an instance of the sortedlist class before we perform any operations like add, delete, etc. like as shown below.

 

SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();

If you observe the above sortedlist declaration, we created a generic sortedlist (slst) with an instance of sortedlist class using type parameters (TKey, TValue) as placeholders with an angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate that the sortedlist is a generic type and type parameter TKey represents a type of keys to be accepted by sortedlist, and TValue is used to represent a type of values to be accepted by sortedlist.

C# SortedList Initialization

Following is the example of initializing a generic sortedlist by specifying a required type for key and value.

 

SortedList<string, int> slist = new SortedList<string, int>();

If you observe the above example, we defined a sortedlist (slist) with the required key and value types to store. Here, the sortedlist will store a key of string type and value of int type.

 

Internally, the sortedlist will maintain two objects[] arrays, one for keys and another for values. When we add key/value pair, it will perform a binary search using the key to find an appropriate index to store a key and value in respective arrays.

C# SortedList Properties

The following are some of the commonly used properties of generic sortedlist in c# programming language.

 

PropertyDescription
Capacity It is used to get or set the number of elements a sortedlist can contain.
Count It is used to get the number of key/value pair elements in the list.
Item[TKey] It is used to get or set the value associated with the specified key.
Keys It is used to get a collection of keys in a sortedlist.
Values It is used to get a collection of values in a sortedlist.

C# SortedList Methods

The following are some of the commonly used methods of generic sortedlist to perform add, search, insert, delete or sort operations in the c# programming language.

 

MethodDescription
Add It is used to add elements with specified key and value in SortedList<TKey, TValue>.
Clear It will remove all the elements from SortedList<TKey, TValue>.
ContainsKey It is used to determine whether the specified key exists in the SortedList<TKey, TValue> or not.
ContainsValue It is used to determine whether the specified value exists in SortedList<TKey, TValue> or not.
IndexOfKey It is used to get the index value of the specified key stored in the SortedList<TKey, TValue>.
IndexOfValue It is used to get the index value of specified value stored in the SortedList<TKey, TValue>.
Remove It is used to remove an element from SortedList<TKey, TValue> with the specified key.
RemoveAt It is used to remove an element at the specified index position from SortedList<TKey, TValue>.
TryGetValue It is used to get the value associated with the specified key.

C# Add Elements to SortedList

In c#, while adding elements to sortedlist, we need to make sure that there will not be any duplicate keys because sortedlist will allow us to store duplicate values, but keys must be unique to identify the values in the list.

 

Following is the example of adding key/value pair elements to a sorted list in different ways.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
        static void Main(string[] args)
        {
           //Create a new sorted list with int keys and string values.
           SortedList<int, string> slst = new SortedList<int, string>();
           // Add elements to the list. No duplicate keys allowed but values can be duplicate
           slst.Add(1, "Suresh");
           slst.Add(4, "Rohini");
           slst.Add(2, "Trishi");
           slst.Add(3, null);
           // Another way to add elements. If key not exist, then that key adds a new key/value pair.
           slst[5] = "Trishi";
           // Add method throws exception if key already in the list
           try
           {
              slst.Add(2, "Praveen");
           }
           catch (ArgumentException)
           {
              Console.WriteLine("An element with Key = '2' already exists.");
           }
           Console.WriteLine("*********List1 Elements********");
           // Accessing elements as KeyValuePair objects.
           foreach (KeyValuePair<int, string> item in slst)
           {
              Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
           }

           // Creating and initializing list
           SortedList<string, int?> slst2 = new SortedList<string, int?> {
                                                {"msg2", 1},
                                                {"msg3", 20},
                                                {"msg4", 100},
                                                {"msg1", null}
                                            };
           Console.WriteLine("*********List2 Elements********");
           // Accessing elements as KeyValuePair objects.
           foreach (KeyValuePair<string, int?> item in slst2)
           {
              Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
           }
           Console.ReadLine();
        }
    }
}

If you observe the above example, we are able to define a new generic sortedlist (slst, slst2) collections by using System.Collections.Generic namespace. Here, we added only the defined data type keys and values to the newly created lists (slst, slst2) in different ways.

 

As discussed, the Add method will throw an exception if we try to add a key (2) that is already existing, so to handle that exception, we used a try-catch block.

 

When you execute the above c# program, we will get the result as shown below.

 

C# Add Elements to SortedList Example Result

 

If you observe the above result, by default all the list elements are sorted in ascending order based on the key, and we got an exception when we tried to add a key (2) that is already existing and added a key (5) which is not existing in the list.

C# Access SortedList Elements

In c#, we have different ways to access sorted list elements, i.e., either using index positions or by iterating through the list using for / foreach loops.

 

Following is the example of accessing the sortedlist elements in different ways.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new sorted list
            SortedList<int, string> slst = new SortedList<int, string>();
            slst.Add(1, "Suresh");
            slst.Add(4, "Rohini");
            slst.Add(2, "Trishi");
            slst.Add(3, "Praveen");
            // Access value with key
            string val1 = slst[2];
            // Access value with index position
            string val2 = slst.Values[2];
            // Access key with index position
            int val3 = slst.Keys[2];
            Console.WriteLine("******Access Elements with Key, Index Position*****");
            Console.WriteLine("Value at Key '2': " + val1);
            Console.WriteLine("Value at Index '2': " + val2);
            Console.WriteLine("Key at Index '2': " + val3);
            Console.WriteLine("*********Access Elements with Foreach Loop********");
            foreach (KeyValuePair<int, string> item in slst)
            {
                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
            }
            Console.WriteLine("*********Access Elements with For Loop********");
            for (int i = 0; i < slst.Count; i++)
            {
                Console.WriteLine("Key = {0}, Value = {1}", slst.Keys[i], slst.Values[0]);
            }
            Console.WriteLine("*********Sorted List Keys********");
            foreach (var item in slst.Keys)
            {
               Console.WriteLine("Key = {0}", item);
            }
            Console.WriteLine("*********Sorted List Values********");
            foreach (var item in slst.Values)
            {
               Console.WriteLine("Value = {0}", item);
            }
            Console.ReadLine();
        }
    }
}

If you observe the above example, we are accessing generic list elements in different ways by using index positions for and foreach loops based on our requirements.

 

When you execute the above c# program, we will get the result as shown below.

 

C# Access SortedList Elements Example Result

C# Remove Elements from SortedList

In c#, we have different methods to remove elements from the sorted list, i.e., either using Remove() or RemoveAt() methods.

 

Following is the example of deleting elements from the sorted list in the c# programming language.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
           //Create a new sorted list
           SortedList<int, string> slst = new SortedList<int, string>();
           slst.Add(1, "Suresh");
           slst.Add(4, "Rohini");
           slst.Add(2, "Trishi");
           slst.Add(3, "Praveen");
           slst.Add(5, "Sateesh");
           // Remove element with key 2
           slst.Remove(2);
           // Remove element at index position 2
           slst.RemoveAt(2);
           Console.WriteLine("*********Access Sorted List Elements********");
           Console.WriteLine();
           foreach (KeyValuePair<int, string> item in slst)
           {
              Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
           }
           Console.ReadLine();
       }
    }
}

If you observe the above example, we used a Remove() method to delete a particular key of elements from the list. We used a RemoveAt() method to delete an element at a specified index position.

 

When you execute the above c# program, you will get the result as shown below.

 

C# Remove Elements from SortedList Example Result

 

If you want to remove all the elements from the sorted list, then use the Clear() method.

C# SortedList Check If Item Exists

By using ContainsKey() and ContainsValue() methods, you can check whether the specified element exists in a sorted list or not. If it exists, these methods will return true otherwise false.

 

Following is the example of using ContainsKey() and ContainsValue() methods to check for an item that exists in a sorted list or not in c#.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          //Create a new sorted list
          SortedList<int, string> slst = new SortedList<int, string>();
          slst.Add(1, "Suresh");
          slst.Add(4, "Rohini");
          slst.Add(2, "Trishi");
          slst.Add(3, "Praveen");
          slst.Add(5, "Sateesh");
          Console.WriteLine("Contains Key 2: {0}", slst.ContainsKey(2));
          Console.WriteLine("Contains Value 'Tutlane': {0}", slst.ContainsValue("Tutlane"));
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a ContainsKey() and ContainsValue() methods to check for particular keys and values that exist in the sorted list (slst) or not.

 

When you execute the above c# program, we will get the result as shown below.

 

Contains Key 2: True

Contains Value 'Tutlane': False

C# SortedList (SortedList<TKey, TValue>) Overview

The following are the important points that need to remember about the sorted list in c#.

 

  • SortedList is used to store a collection of key/value pairs sorted by key based on the associated IComparer<T> implementation.
  • SortedList will allow us to store duplicate values, but keys must be unique to identify the values in the sorted list.
  • In SortedList, the keys cannot be null, but the values can be null.
  • You can access SortedList elements either by using keys, index positions, or with for and foreach loops. In the foreach loop, we need to use KeyValuePair<TKey, TValue> to get key/value pairs from SortedList.