How to remove elements from the SortedDictionary?
In SortedDictionary, it is allowed to remove elements from the SortedDictionary. SortedDictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:
- Clear(): This method is used to remove all elements from the SortedDictionary.
- Remove(TKey): This method is used to remove the element with the specified key from the SortedDictionary.
Example:
CSharp
// C# program to illustrate how to // Remove key/value pair from the // SortedDictionary using System; using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating sorted dictionary // Using SortedDictionary class SortedDictionary< int , string > My_sdict = new SortedDictionary< int , string >(); // Adding key/value pair in // SortedDictionary Using // the Add() method My_sdict.Add(001, "Google"); My_sdict.Add(002, "Bing"); My_sdict.Add(003, "Yahoo"); My_sdict.Add(004, "Ask.com"); My_sdict.Add(005, "AOL.com"); // Initial number of key/value pairs Console.WriteLine("Key/Value pair: {0}", My_sdict.Count); // After using Remove(TKey) method My_sdict.Remove(002); Console.WriteLine("Key/Value pair: {0}", My_sdict.Count); // After using Clear() method My_sdict.Clear(); Console.WriteLine("Key/Value pair: {0}", My_sdict.Count); } } |
Output
Key/Value pair: 5 Key/Value pair: 4 Key/Value pair: 0
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