C# Hashtable Example
A hash table is a collection that is used to store key-value pairs. So the hash table stores 2 values while storing just one value like the stack, array list and queue. These 2 values are an element of the hash table.
- To add an element to the queue, the Add method is used. The statement’s general syntax is given below.
ht.Add("key", "Value");
- ContainsKey method is used to determine whether the Hashtable contains a specific key.
- ContainsValue method is used to determine whether the Hashtable contains a specific value.
When you use foreach to enumerate hash table elements, the elements are retrieved as KeyValuePair objects.
foreach (DictionaryEntry de in ht)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
Hastable Example:
Hashtable ht = new Hashtable();
// Add key-value pairs
ht.Add("key1", "Value1");
ht.Add("key2", "Value2");
ht.Add("key3", "Value3");
bool hasKey1 = ht.ContainsKey("key1");
bool hasValue2 = ht.ContainsValue("Value1");
// When you use foreach to enumerate hash table elements,
// the elements are retrieved as KeyValuePair objects.
foreach (DictionaryEntry de in ht)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
