How to remove elements from the hashtable?
In Hashtable, you are allowed to remove elements from the hashtable. The Hashtable class provides two different methods to remove elements and the methods are:
Example:
C#
// C# program to illustrate how // remove elements from the hashtable using System; using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable = new Hashtable(); // Adding key/value pair // in the hashtable // Using Add() method my_hashtable.Add( "A1" , "Welcome" ); my_hashtable.Add( "A2" , "to" ); my_hashtable.Add( "A3" , "w3wiki" ); // Using remove method // remove A2 key/value pair my_hashtable.Remove( "A2" ); Console.WriteLine( "Key and Value pairs :" ); foreach (DictionaryEntry ele1 in my_hashtable) { Console.WriteLine( "{0} and {1} " , ele1.Key, ele1.Value); } // Before using Clear method Console.WriteLine( "Total number of elements present" + " in my_hashtable:{0}" , my_hashtable.Count); my_hashtable.Clear(); // After using Clear method Console.WriteLine( "Total number of elements present in" + " my_hashtable:{0}" , my_hashtable.Count); } } |
Key and Value pairs : A3 and w3wiki A1 and Welcome Total number of elements present in my_hashtable:2 Total number of elements present in my_hashtable:0
C# Hashtable with Examples
A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. In other words, a Hashtable is used to create a collection that uses a hash table for storage. It generally optimizes the lookup by calculating the hash code of every key and storing it into another basket automatically and when you access the value from the hashtable at that time it matches the hashcode with the specified key. It is the non-generic type of collection that is defined in the System. Collections namespace.
Important Points:
- In Hashtable, the key cannot be null, but the value can be.
- In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable.
- The capacity of a Hashtable is the number of elements that Hashtable can hold.
- A hash function is provided by each key object in the Hashtable.
- The Hashtable class implements the IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, and ICloneable interfaces.
- In the hashtable, you can store elements of the same type and of the different types.
- The elements of the hashtable that is a key/value pair are stored in DictionaryEntry, so you can also cast the key/value pairs to a DictionaryEntry.
- that key that must be unique. Duplicate keys are not allowed.