StringDictionary.Remove(String) method is used to remove the entry with the specified key from the string dictionary.
Syntax:
public virtual void Remove (string key);
Here, key is the key of the entry to remove.
Exceptions:
- ArgumentNullException: If the key is null.
- NotSupportedException: If the StringDictionary is read-only.
Below programs illustrate the use of StringDictionary.Remove(String) method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
myDict.Add( "E" , "Elephant" );
myDict.Add( "F" , "Fish" );
Console.WriteLine( "The number of key/value pairs are : " + myDict.Count);
foreach (DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
myDict.Remove( "D" );
Console.WriteLine( "The number of key/value pairs are : " + myDict.Count);
foreach (DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
}
}
|
Output:
The number of key/value pairs are : 6
b Banana
c Cat
a Apple
f Fish
d Dog
e Elephant
The number of key/value pairs are : 5
b Banana
c Cat
a Apple
f Fish
e Elephant
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
myDict.Add( "E" , "Elephant" );
myDict.Add( "F" , "Fish" );
Console.WriteLine( "The number of key/value pairs are : " + myDict.Count);
foreach (DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
myDict.Remove( null );
Console.WriteLine( "The number of key/value pairs are : " + myDict.Count);
foreach (DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: key
Note:
- If the StringDictionary does not contain an element with the specified key, the StringDictionary remains unchanged. No exception is thrown.
- The key is handled in a case-insensitive manner, i.e, it is translated to lowercase before it is used to find the entry to remove from the StringDictionary.
- This method is an O(1) operation.
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!