Home C# Tutorial on SortedDictionary in C#

Tutorial on SortedDictionary in C#

The SortedDictionary<K, V> class in C# is part of the System.Collections.Generic namespace. Like Dictionary<K, V>, it stores key-value pairs, but it keeps the keys sorted in ascending order.

SortedDictionary<K, V> is ideal when you need to maintain elements in a sorted order while allowing efficient lookups, insertions, and deletions by key.

In this tutorial, we’ll cover:

1. Creating a SortedDictionary<K, V>

To create a SortedDictionary<K, V>, include the System.Collections.Generic namespace. K is the type of the key, and V is the type of the value.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        // Create an empty sorted dictionary of string keys and int values
        SortedDictionary<string, int> ages = new SortedDictionary<string, int>();

        // Create a sorted dictionary with initial values
        SortedDictionary<string, string> capitals = new SortedDictionary<string, string> {
            { "USA", "Washington, D.C." },
            { "France", "Paris" },
            { "Japan", "Tokyo" }
        };

        Console.WriteLine("Initial capitals sorted dictionary:");
        foreach (var item in capitals) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Initial capitals sorted dictionary:
France: Paris
Japan: Tokyo
USA: Washington, D.C.

In this example:

  • SortedDictionary<string, int> ages = new SortedDictionary<string, int>(); creates an empty sorted dictionary.
  • SortedDictionary<string, string> capitals initializes a sorted dictionary with key-value pairs representing countries and their capitals. The output shows that the keys are automatically sorted in alphabetical order.

2. Adding Elements to the Sorted Dictionary

You can add elements to a sorted dictionary using the Add method or by using the indexer [].

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> ages = new SortedDictionary<string, int>();

        // Adding elements with Add
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);

        // Adding elements with indexer
        ages["Charlie"] = 35;

        Console.WriteLine("Ages sorted dictionary:");
        foreach (var item in ages) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Ages sorted dictionary:
Alice: 30
Bob: 25
Charlie: 35

In this example:

  • Add(“Alice”, 30) adds a key-value pair using Add.
  • ages[“Charlie”] = 35; adds or updates a key-value pair using the indexer.

Note: Adding a duplicate key with Add will throw an ArgumentException.

3. Accessing and Modifying Elements

You can access and modify elements in a sorted dictionary using the key as an index.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> ages = new SortedDictionary<string, int> {
            { "Alice", 30 },
            { "Bob", 25 }
        };

        // Access elements
        Console.WriteLine("Alice's age: " + ages["Alice"]);

        // Modify an existing element
        ages["Alice"] = 31;

        Console.WriteLine("Updated Alice's age: " + ages["Alice"]);
    }
}

Output:

Alice's age: 30
Updated Alice's age: 31

In this example:

  • ages[“Alice”] accesses Alice’s age.
  • ages[“Alice”] = 31; updates Alice’s age to 31.

Note: Attempting to access a non-existent key with [] will throw a KeyNotFoundException. Use TryGetValue to avoid this.

Using TryGetValue to Access Elements Safely

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> ages = new SortedDictionary<string, int> { { "Alice", 30 } };

        if (ages.TryGetValue("Bob", out int age)) {
            Console.WriteLine("Bob's age: " + age);
        } else {
            Console.WriteLine("Bob is not in the dictionary.");
        }
    }
}

Output:

Bob is not in the dictionary.

4. Removing Elements

You can remove elements from a sorted dictionary using Remove or Clear.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> ages = new SortedDictionary<string, int> {
            { "Alice", 30 },
            { "Bob", 25 },
            { "Charlie", 35 }
        };

        // Remove a specific element by key
        ages.Remove("Bob");

        // Clear all elements from the sorted dictionary
        ages.Clear();

        Console.WriteLine("Ages sorted dictionary count after clearing: " + ages.Count);
    }
}

Output:

Ages sorted dictionary count after clearing: 0

In this example:

  • Remove(“Bob”) removes the entry with the key “Bob”.
  • Clear() removes all entries from the dictionary.

5. Checking for Keys and Values

You can check if a sorted dictionary contains a specific key or value using ContainsKey and ContainsValue.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> ages = new SortedDictionary<string, int> {
            { "Alice", 30 },
            { "Bob", 25 }
        };

        // Check if a key exists
        Console.WriteLine("Contains key 'Alice': " + ages.ContainsKey("Alice"));

        // Check if a value exists
        Console.WriteLine("Contains value 25: " + ages.ContainsValue(25));
    }
}

Output:

Contains key 'Alice': True
Contains value 25: True

In this example:

  • ContainsKey(“Alice”) checks if the key “Alice” exists.
  • ContainsValue(25) checks if the value 25 exists.

6. Iterating Through a Sorted Dictionary

You can iterate through a sorted dictionary using a foreach loop to access both keys and values. The items are iterated in sorted order of the keys.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, string> capitals = new SortedDictionary<string, string> {
            { "USA", "Washington, D.C." },
            { "France", "Paris" },
            { "Japan", "Tokyo" }
        };

        Console.WriteLine("Country capitals:");
        foreach (KeyValuePair<string, string> item in capitals) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Country capitals:
France: Paris
Japan: Tokyo
USA: Washington, D.C.

In this example:

  • The foreach loop iterates over each KeyValuePair<string, string>, and the items are displayed in the sorted order of the keys.

7. Practical Examples of SortedDictionary<K, V> in Real Scenarios

Example 1: Storing Product Prices in Alphabetical Order

You can use a sorted dictionary to store product prices sorted by product names.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, decimal> products = new SortedDictionary<string, decimal> {
            { "Apples", 1.20m },
            { "Bananas", 0.75m },
            { "Cherries", 2.50m }
        };

        Console.WriteLine("Product prices:");
        foreach (var item in products) {
            Console.WriteLine($"{item.Key}: ${item.Value}");
        }
    }
}

Output:

Product prices:
Apples: $1.20
Bananas: $0.75
Cherries: $2.50

In this example:

  • The sorted dictionary maintains the alphabetical order of product names.

Example 2: Ranking Players by Scores in Ascending Order

A SortedDictionary<K, V> can store player scores sorted by player names in ascending order.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedDictionary<string, int> playerScores = new SortedDictionary<string, int> {
            { "Alice", 120 },
            { "Bob", 150 },
            { "Charlie", 130 }
        };

        Console.WriteLine("Player Scores:");
        foreach (var item in playerScores) {
            Console.WriteLine($"{item.Key}: {item.Value} points");
        }
    }
}

Output:

Player Scores:
Alice: 120 points
Bob: 150 points
Charlie: 130 points

In this example:

  • The sorted dictionary maintains

players’ scores in alphabetical order by player name.

Summary

In this tutorial, we covered the SortedDictionary<K, V> class in C# and demonstrated its features:

  1. Creating a SortedDictionary<K, V>: Initializing sorted dictionaries with or without initial values.
  2. Adding Elements: Using Add and indexer [] to add items.
  3. Accessing and Modifying Elements: Using keys to access and modify values, and TryGetValue for safe access.
  4. Removing Elements: Using Remove and Clear.
  5. Checking for Keys and Values: Using ContainsKey and ContainsValue.
  6. Iterating Through a Sorted Dictionary: Using foreach to access both keys and values in sorted order.
  7. Practical Examples: Storing product prices and player scores in sorted order.

The SortedDictionary<K, V> class is a powerful and efficient collection type for managing sorted key-value pairs, making it ideal for applications requiring sorted lookups, such as storing alphabetized lists, ranking systems, and other order-sensitive data.

 

You may also like