In C#, SortedDictionary<TKey, TValue>
is a generic class that represents a collection of key/value pairs, where the keys are sorted based on their natural order or a custom comparer. It is part of the System.Collections.Generic
namespace.
Here’s an overview of the SortedDictionary<TKey, TValue>
class:
- It provides a key-value mapping, where each key must be unique within the collection.
- Keys are sorted in ascending order by default, but you can provide a custom comparer to define a different sorting order.
- It internally uses a red-black tree data structure to efficiently maintain the sorted order of the keys.
- The key type (
TKey
) must implement theIComparable<TKey>
interface, or you can provide a custom comparer during initialization. - The value type (
TValue
) can be any type.
Here’s an example of how to use SortedDictionary<TKey, TValue>
:
using System; using System.Collections.Generic; class Program { static void Main() { // Create a SortedDictionary with string keys and int values SortedDictionary<string, int> ages = new SortedDictionary<string, int>(); // Add key/value pairs ages.Add("John", 30); ages.Add("Alice", 25); ages.Add("Bob", 35); // Access values by key Console.WriteLine(ages["John"]); // Output: 30 // Check if a key exists if (ages.ContainsKey("Alice")) { // Update the value for an existing key ages["Alice"] = 26; } // Iterate over key/value pairs foreach (var kvp in ages) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } /* Output: Alice: 26 Bob: 35 John: 30 */ } }
In the example above, we create a SortedDictionary<string, int>
called ages
, where the keys are strings representing names and the values are integers representing ages. We add some key/value pairs, access values by key, update a value, and iterate over the key/value pairs. The SortedDictionary
automatically maintains the keys in sorted order based on the default comparison of string keys.