OrderedDictionary.Remove(Object) method is used to remove entry with the specified key from the OrderedDictionary collection.
Syntax:
public void Remove (object key);
Here, key is the key of the entry to remove.
Exceptions:
- NotSupportedException : If the OrderedDictionary collection is read-only.
- ArgumentNullException : If the key is null.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
Console.WriteLine( "Number of elements are : "
+ myDict.Count);
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " -- " + de.Value);
myDict.Remove( "key2" );
Console.WriteLine( "Number of elements are : "
+ myDict.Count);
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " -- " + de.Value);
}
}
|
Output:
Number of elements are : 5
key1 -- value1
key2 -- value2
key3 -- value3
key4 -- value4
key5 -- value5
Number of elements are : 4
key1 -- value1
key3 -- value3
key4 -- value4
key5 -- value5
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
Console.WriteLine( "Number of elements are : "
+ myDict.Count);
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " -- " + de.Value);
myDict.Remove( null );
Console.WriteLine( "Number of elements are : "
+ myDict.Count);
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " -- " + de.Value);
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: key
Note:
- The entries that follow the removed entry move up to occupy the vacated spot and the indexes of the entries that get moved are also updated.
- If the OrderedDictionary collection does not contain an entry with the specified key, the OrderedDictionary remains unchanged and no exception is thrown.
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!
Last Updated :
01 Feb, 2019
Like Article
Save Article