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
Understanding `SortedDictionary` and its `Keys` Property
The `SortedDictionary
`Keys` Property Syntax
SortedDictionary<TKey, TValue>.KeyCollection keys = mySortedDictionary.Keys;
The `Keys` property returns a `KeyCollection
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) ...
}
}