C# SortedList

C# collections

In C#, SortedList is a collection that is automatically sorted by key. It stores data as key-value pairs and automatically sorts by key order (ascending) when adding or updating.

The SortedList class represents a collection of key/value pairs sorted by key.key => valueThese key/value pairs can be accessed by key and by index.

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 a dynamic array (ArrayList); if you access items using a key, it is a hash table (Hashtable). The items in the collection are always sorted by key value.

SortedList has two versions:

  1. non-genericSortedList(System.Collections.SortedList)
  2. GenericsSortedList<TKey, TValue>(System.Collections.Generic.SortedList<TKey, TValue>)

Features:

  • Automatic sorting: All keys are sorted in ascending order; there is no need to manually call a sorting method.
  • Key-value pair storage: Each key is unique; the value associated with it can be repeated.
  • Dynamically adjust capacity: Automatically adjusts the size of internal storage as needed.
  • Index accessAccess data by key or index.
  • Efficient operations: The average time complexity of retrieval, insertion, and deletion is O(log n).

Methods and properties of the SortedList class

The table below listsSortedListSome common uses of the classProperty:

Attribute NameTypeDescription
CountintGet the number of key-value pairs in the sorted list.
CapacityintGet or set the capacity of the sorted list.
ComparerIComparerorIComparer<TKey>Gets the comparer used to sort the keys.
IsReadOnlyboolIndicates whether the sorted list is read-only.
IsFixedSizeboolIndicates whether the sorted list has a fixed size (alwaysfalse)。
KeysICollectionorIList<TKey>Get all keys in the sorted list.
ValuesICollectionorIList<TValue>Get all values in the sorted list.

The table below listsSortedListSome common uses of the classMethods:

Method NameReturn TypeDescription
Adding and removing
Add(TKey key, TValue value)voidAdds the specified key/value pair to the sorted list.
Remove(TKey key)boolRemoves the element with the specified key from the sorted list.
RemoveAt(int index)voidRemoves the key/value pair at the specified index in the sorted list.
Clear()voidRemove all elements from the sorted list.
Searching and accessing
ContainsKey(TKey key)boolDetermines whether the sorted list contains the specified key.
ContainsValue(TValue value)boolDetermines whether the sorted list contains the specified value.
IndexOfKey(TKey key)intReturns the index of the specified key.
IndexOfValue(TValue value)intReturns the index of the specified value.
TryGetValue(TKey key, out TValue value)boolGets the value associated with the specified key, and returns it if it exists.true。
Copying and enumerating
CopyTo(Array array, int index)voidCopies the elements of the sorted list to an array, starting at the specified index.
GetEnumerator()IEnumeratorReturns an enumerator used to iterate through the elements in the sorted list.

Example

The following example demonstrates the concept of SortedList.

Non-generic version operations:

Example

using System;
using System.Collections;

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

         sl.Add("001", "Zara Ali");
         sl.Add("002", "Abida Rehman");
         sl.Add("003", "Joe Holzner");
         sl.Add("004", "Mausam Benazir Nur");
         sl.Add("005", "M. Amlan");
         sl.Add("006", "M. Arif");
         sl.Add("007", "Ritesh Saikia");

         if (sl.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the list");
         }
         else
         {
            sl.Add("008", "Nuha Ali");
         }

         // Get the collection of keys
         ICollection key = sl.Keys;

         foreach (string k in key)
         {
            Console.WriteLine(k + ": " + sl[k]);
         }
      }
   }
}

When the above code is compiled and executed, it produces the following results:

001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Banazir Nur
005: M. Amlan 
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali

Generic version:

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a generic SortedList
        SortedList<int, string> sortedList = new SortedList<int, string>();

        // Add key-value pair
        sortedList.Add(2, "Banana");
        sortedList.Add(1, "Apple");
        sortedList.Add(3, "Cherry");

        // Automatically sort by key
        Console.WriteLine("SortedList contents:");
        foreach (var kvp in sortedList)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // Lookup and access
        Console.WriteLine($"\nValue for key 2: {sortedList[2]}"); // Output: Banana

        // Delete elements
        sortedList.Remove(1);
        Console.WriteLine("\nAfter removing key 1:");
        foreach (var kvp in sortedList)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // Check key and value
        Console.WriteLine($"\nContains key 3: {sortedList.ContainsKey(3)}"); // output: True
        Console.WriteLine($"Contains value 'Apple': {sortedList.ContainsValue("Apple")}"); // Output: False
    }
}

C# collections

other extensions