Introduction
A hashtable is a collection that uses key/value pairs and the key is subsequently used to create a hash code which is used in the organization of the key/value pairs.
There are certain points one must remember when dealing with hash tables:
-
Keys cannot have a null value, but values can.
-
Keys have to be unique in a hashtable. You cannot have duplicate keys.
-
DictionaryEntry is used to store the contents of a hashtable (key/value pairs).
-
You can insert and store in a hashtable elements that are either the same or different types.
-
A hashtable is as large as the number of elements contained within it.
Creating a hashtable
Import the System.Collections
namespace:
using System.Collections;
Create a hashtable:
Hashtable nameOfHashtable = new Hashtable();
Add elements to a hashtable
We use the Add
method in order to insert elements into a hashtable:
Hashtable hashTableExample = new Hashtable();
hashTableExample.Add("LL", "Lower Level");
hashTableExample.Add("S1", "Suite Level 1");
hashTableExample.Add("P1", "Penthouse Level 1");
Remove elements from a hashtable
We use the Remove
method in order to remove a single element at a time from the hashtable using the key.
hashTableExample.Remove("S1");
We use the Clear
method in order to clear the entire hashtable:
hashTableExample.Clear();
Check if a key exists
The Contains
and ContainsKey
methods can be used to check whether a key exists:
hashTableExample.Contains("LL"); //True
hashTableExample.ContainsKey("S1"); //False
Check if a value exists
The ContainsValue
method can be used to check whether a value exists:
hashTableExample.ContainsValue("Lower Level"); //True
Output elements of a hashtable
In order to output the elements of a hashtable we use a foreach loop and loop over the hashtable as a dictionary:
foreach(DictionaryEntry element in hashTableExample)
{
Console.WriteLine("{0} and {1} ", element.Key, element.Value);
}
/* P1 and Penthouse Level 1
* S1 and Suite Level 1
* LL and Lower Level
*/