How to delete an item from a HashTable in C#:
Hashtables are used to store key-value pairs in C sharp. We can use the key to access the value linked to that key. Also, we can use the key to make any editing in the hash table.
To delete an item from a HashTable in C#, we have a method called Remove. This method is used to delete an item from a hashtable. In this post, we will learn how to use Remove method with an example.
Definition of Remove:
The Remove method is defined as below:
public virtual void Remove(Object key);
Here, key is the key of the element in the HashTable that we are removing from the hashtable.
Example of Remove:
Let’s take a look at an example on how to use Remove.
using System;
using System.Collections;
public class Program {
public static void Main(string[] args) {
var givenItems = new Hashtable(){{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}};
Console.WriteLine("Current Keys: ");
foreach(int key in givenItems.Keys){
Console.Write(key+" ");
}
Console.WriteLine("\nRemoving key 2");
givenItems.Remove(2);
Console.WriteLine("Current Keys: ");
foreach(int key in givenItems.Keys){
Console.Write(key+" ");
}
}
}
Here,
- givenItems is the original HashTable that is created with a couple of key-value pairs.
- We are printing all keys of the HashTable before removing an item from the hashtable and after an item is removed.
- Using Remove, we are removing the item with key 2.
Output:
This program will print the below output:
Current Keys:
4 3 2 1
Removing key 2
Current Keys:
4 3 1
Exceptions in Remove:
This method can throw exceptions. It can throw any of the following exceptions:
ArgumentNullException:
It throws ArgumentNullException if the key is null.
NotSupportedException:
It throws NotSupportedException if the hash table has fixed size or if it is read-only.