Accessing Keys in a C# `SortedDictionary` using the `Keys` Property

Learn how to efficiently access and iterate through the keys in a C# `SortedDictionary` using the `Keys` property. This tutorial explains the `KeyCollection`, demonstrates iteration techniques, and highlights important considerations for working with this read-only collection.



Accessing Keys in a C# `SortedDictionary` Using the `Keys` Property

In C#, a `SortedDictionary` stores key-value pairs in a sorted order based on the key. The `Keys` property provides a convenient way to access and iterate over only the keys within the dictionary.

Understanding `SortedDictionary` and its `Keys` Property

The `SortedDictionary` class maintains a sorted collection of key-value pairs, where keys must be unique and comparable. The `Keys` property gives you access to a `KeyCollection`, which is a read-only collection containing all the keys from the `SortedDictionary`.

`Keys` Property Syntax


SortedDictionary<TKey, TValue>.KeyCollection keys = mySortedDictionary.Keys;

The `Keys` property returns a `KeyCollection`, which is an immutable (read-only) collection. Attempting to modify this collection will result in a `NotSupportedException`.

Characteristics of `SortedDictionary.Keys`

  • Ordered Collection: Keys are returned in sorted order (based on the natural ordering of `TKey` or a custom comparer).
  • Immutable: The `KeyCollection` cannot be directly modified.
  • Access Complexity: Accessing the entire collection is O(1) (constant time).
  • Iteration Complexity: Iterating through all keys is O(n) (linear time).

Example 1: Accessing Keys in a String-Based Dictionary


using System;
using System.Collections.Generic;

public class SortedDictionaryExample {
    public static void Main(string[] args) {
        SortedDictionary<string, string> myDict = new SortedDictionary<string, string>();
        // ... (add key-value pairs) ...
        // ... (access keys using Keys property and print them) ...
    }
}

Example 2: Accessing Keys in an Integer-Based Dictionary


using System;
using System.Collections.Generic;

public class SortedDictionaryExample {
    public static void Main(string[] args) {
        SortedDictionary<int, string> myDict = new SortedDictionary<int, string>();
        // ... (add key-value pairs) ...
        // ... (access keys using Keys property and print them) ...
    }
}