Diving into Sorted Dictionaries in C#

Diving into Sorted Dictionaries in C#

Hello again! This lesson's topic is Sorted Dictionaries. Similar to other dictionary structures, Sorted Dictionaries store key-value pairs but in an ordered manner. Learning about Sorted Dictionaries enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Sorted Dictionaries using C#'s SortedDictionary class.

Introduction: Sorted Dictionaries in C#

In C#, we differentiate between regular dictionaries like Dictionary and Sorted Dictionaries. Comparing Dictionary to SortedDictionary is akin to comparing a messy bookshelf to a well-organized library — the latter maintains order. Dictionary does not guarantee any order of keys, whereas SortedDictionary sorts the keys in natural order (if they implement the IComparable interface) or according to a specified comparator.

The SortedDictionary class is part of the System.Collections.Generic namespace and provides a binary search tree-based implementation of the IDictionary<TKey, TValue> interface. This ensures that the dictionary is always sorted according to the natural ordering of its keys or by a custom comparator.

Discovering SortedDictionary

To create a SortedDictionary object, you can either use the default constructor or initialize it with a dictionary. The keys used in a SortedDictionary must be immutable and comparable. For instance:

using System;
using System.Collections.Generic;

public class SortedDictionaryExample
{
    public static void Main(string[] args)
    {
        // SortedDictionary with fruits as keys and corresponding counts as values
        SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>();
        sortedDict["banana"] = 3;
        sortedDict["apple"] = 4;
        sortedDict["pear"] = 1;
        sortedDict["orange"] = 2;

        // Print the SortedDictionary
        foreach (var item in sortedDict)
        {
            Console.WriteLine($"{item.Key}={item.Value}");
        }
    }
}

The output will be:

apple=4
banana=3
orange=2
pear=1

In this example, the keys are sorted in alphabetical order. This means that "apple" comes first because 'a' is earlier in the alphabet than 'b' from "banana", 'o' from "orange", and 'p' from "pear". Conversely, "pear" is the greatest key because 'p' has a higher ASCII value than 'a', 'b', and 'o'.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal