Efficiently Clearing C#'s `SortedDictionary`: Removing All Key-Value Pairs with `Clear()`
Learn how to use C#'s `SortedDictionary
Understanding and Using `SortedDictionary.Clear()` in C#
Introduction
In C#, a `SortedDictionary` is a collection that stores key-value pairs, keeping the keys sorted in ascending order. The `Clear()` method provides a way to efficiently remove all elements from the `SortedDictionary`.
What is a `SortedDictionary`?
A `SortedDictionary` (found in the `System.Collections.Generic` namespace) is a dynamic collection. This means its size adjusts automatically as you add or remove items. Key characteristics include:
- Unique Keys: Keys must be unique; duplicates are not allowed.
- Immutable Keys: Keys cannot be changed after they are added.
- Null Keys: Keys cannot be
null
. - Null Values: Values can be
null
(if the value type is a reference type). - Fast Inserts and Deletes: `SortedDictionary` is optimized for efficient addition and removal of elements.
- Homogeneous Key-Value Pairs: Keys and values must be of the same type.
`SortedDictionary.Clear()` Method
The `Clear()` method removes all key-value pairs from the `SortedDictionary`. After calling `Clear()`, the dictionary is empty.
Method Signature
`SortedDictionary.Clear()` Signature
public void Clear();
Example 1: Clearing a String-Based `SortedDictionary`
Example 1: Clearing a String SortedDictionary
using System;
using System.Collections.Generic;
class SortedDictionaryClear {
public static void Main() {
SortedDictionary<string, string> dict = new SortedDictionary<string, string>();
dict.Add("Afghanistan", "Kabul");
dict.Add("Sri Lanka", "Colombo");
// ... add more key-value pairs ...
Console.WriteLine($"Initial count: {dict.Count}"); // Output: 8
dict.Clear();
Console.WriteLine($"Count after Clear(): {dict.Count}"); // Output: 0
}
}
Example 2: Clearing an Integer-Based `SortedDictionary`
Example 2: Clearing an Integer SortedDictionary
using System;
using System.Collections.Generic;
class SortedDictionaryClear {
public static void Main() {
SortedDictionary<int, int> dict = new SortedDictionary<int, int>();
dict.Add(1, 11);
dict.Add(2, 22);
// ... add more key-value pairs ...
Console.WriteLine($"Initial count: {dict.Count}"); // Output: 9
dict.Clear();
Console.WriteLine($"Count after Clear(): {dict.Count}"); // Output: 0
}
}
Conclusion
The `SortedDictionary.Clear()` method provides a straightforward way to empty a `SortedDictionary`. This is useful when you need to reset the dictionary or reuse it for a new set of key-value pairs.