How to clear all the elements from the SortedDictionary?
To clear all elements from a SortedDictionary in C#, you can use the Clear() method.
C#
using System; using System.Collections.Generic; class Program { static void Main() { SortedDictionary< string , int > dictionary = new SortedDictionary< string , int >(); // Add key-value pairs to the SortedDictionary dictionary.Add( "Apple" , 10); dictionary.Add( "Banana" , 5); dictionary.Add( "Orange" , 8); // Clear all elements from the SortedDictionary dictionary.Clear(); // Verify that the SortedDictionary is empty Console.WriteLine( "Number of elements in the SortedDictionary: " + dictionary.Count); } } |
Number of elements in the SortedDictionary: 0
In this example, we create a SortedDictionary with string keys and int values. We add three key-value pairs to the dictionary using the Add method. Then, we clear all elements from the SortedDictionary using the Clear method. Finally, we display the count of elements in the SortedDictionary, which should be 0 since we cleared all the elements.
SortedDictionary Implementation in C#
In C#, SortedDictionary is a generic collection that is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need. Important Points:
- The SortedDictionary class implements the
- ICollection<KeyValuePair<TKey, TValue>> Interface
- IDictionary<TKey, TValue> Interface
- IEnumerable<KeyValuePair<TKey, TValue>> Interface
- IEnumerable<T> Interface
- IReadOnlyCollection<KeyValuePair<TKey, TValue>> Interface
- IReadOnlyDictionary<TKey, TValue> Interface
- ICollection Interface
- IDictionary Interface
- IEnumerable Interface
- In SortedDictionary, the key must be unique. Duplicate keys are not allowed.
- In SortedDictionary, the keys are immutable and cannot be null.
- In SortedDictionary, the value can be null when the type of the value is of reference type.
- It provides fastest insertion and removal operations for unsorted data.
- In SortedDictionary, you can only store the same types of key/value pairs.
- The capacity of a SortedDictionary is the number of key/value pairs that SortedDictionary can hold.
- It sort in ascending order.
Contact Us