07 Feb 2024




Intermediate

SortedDictionary<K, V> Generic Collections in C#

Definition:

SortedDictionary<K, V> is a generic collection class in the System.Collections.Generic namespace of C#. It represents a collection of key-value pairs that are sorted by the keys. The keys must be unique and must be immutable. The K represents the type of keys, and V represents the type of values stored in the dictionary.

Key Features and Characteristics:

  • Sorted Order: SortedDictionary<K, V> maintains the elements sorted by their keys in ascending order.
  • Generic Type Parameters: SortedDictionary<K, V> is generic, allowing it to store elements of any data type specified by the developer for both keys and values.
  • Efficient Lookup: Provides efficient lookup times for retrieving values based on their corresponding keys using binary search.
  • Automatic Sorting: Automatically maintains the sorted order of elements based on the keys, ensuring that the keys are always in ascending order.
  • Red-Black Tree Implementation: Internally, SortedDictionary<K, V> uses a red-black tree data structure to maintain the sorted order of elements.
  • Methods and Properties: SortedDictionary<K, V> provides a variety of methods and properties for adding, removing, and accessing elements. Some common methods include Add, Remove, ContainsKey, TryGetValue, Keys, Values, Clear, and more.

Uses:

  • Maintaining a collection of key-value pairs in sorted order.
  • Efficiently looking up values based on their corresponding keys.
  • Implementing sorted dictionaries, maps, or associative arrays in algorithms and data structures.

Advantages:

  • Provides fast lookup times based on binary search, even for large collections.
  • Automatically maintains the sorted order of elements, eliminating the need for manual sorting.
  • Supports generic types, allowing for flexibility in the types of keys and values stored.
  • Efficient for scenarios requiring frequent retrieval of elements based on keys.

Disadvantages:

  • Higher memory overhead compared to unsorted dictionaries due to the additional bookkeeping required for maintaining the sorted order.
  • Slower insertion and removal operations compared to unsorted dictionaries due to the additional sorting overhead.

Code Example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Creating a SortedDictionary with string keys and int values
        SortedDictionary<string, int> scores = new SortedDictionary<string, int>();

        // Adding key-value pairs to the SortedDictionary
        scores.Add("Alice", 85);
        scores.Add("Bob", 92);
        scores.Add("Charlie", 78);

        // Retrieving and displaying the score for a specific student
        if (scores.ContainsKey("Bob"))
        {
            int bobScore = scores["Bob"];
            Console.WriteLine("Bob's score: " + bobScore); // Output: Bob's score: 92
        }

        // Iterating over the key-value pairs in sorted order
        foreach (var kvp in scores)
        {
            Console.WriteLine($"Name: {kvp.Key}, Score: {kvp.Value}");
        }
    }
}

Explanation: This example demonstrates creating a SortedDictionary<string, int> and adding key-value pairs to it. The Add method is used to add elements to the dictionary. The ContainsKey property is used to check if a key exists before accessing its value. The foreach loop is used to iterate over all key-value pairs in the dictionary, which are automatically sorted by keys in ascending order, and print them.

c-sharp
sorteddictionary
generic-collections