Overview
Today, we will see, how hashtables work in C#. Hashtables are nothing but the collection of the key-value pairs. We will see in detail in this blog, so let's start .
Introduction
Hashtable is a collection of the Key-Value pairs, which are organized on the hash code of their respective keys.
When you add an element, it gets added to the hashtable and its corresponding hash code is generated automatically. Here, we are using the keys to access those hashcodes. Hashtable optimizes lookup with the help of the keys.
Syntax
Now, we had created a constructor, using its default constructor.
- Hashtable at=new Hashtable();
Add a Key
Here 1 is the key with its respective values.
Now, you have to use for each loop to display the elements.
For retrieving the elements through the hashtable, use Dictionary Entry.
- foreach(DictionaryEntry e in ht)
- {
- Console.WriteLine(“{
- 0
- }, {
- 1
- }”, e.Key, e.Value);
- }
For checking keys
For checking Value
- int value = (int) ht[“One”];
We need to cast it as the data type
Properties of Hashtable
- Keys: Gets an ICollection, which contains the keys in the Hashtable.
- Values: Gets an ICollection, which contains the values in the Hashtable.
Casting in Hashtable
We can use the ‘as’ operator to attempt to cast an object to a specific reference type. It returns true or false and you also reduce casting by using the ‘is’ operator.
If you want to store the keys in an array list: For storing the keys in an array list, you can use the keys property of Hashtable. For example,
- ArrayList al = new ArrayList(ht.Keys)
-
- foreach(int key in al) r {
- Console.WriteLine(Key);
- }
Advantage of Hashtable
- Hashtable allows the execution time for the lookup, retrieves and sets the operation to remain nearly constant, even for the large sets.
- In the large data sets, Hashtable is an ability to locate the item quickly.
- No need to scan through the entire data sets to find the items.
For example, we create an instance of Hashtable and added four elements in it. Subsequently, we are printing all the elements in the Hashtable and keys given to the array list for containing all the keys of Hashtable and finally printing it.
Example
- using System;
- using System.Collections;
- namespace hasthtab
- {
- class Program
- {
- static void Main(string[] args) {
- Hashtable ht = new Hashtable();
- ht.Add("1", "Akshay");
- ht.Add("2", "Hari");
- ht.Add("3", "Raghvan");
- ht.Add("4", "Milind");
- ICollection key = ht.Keys;
- Console.WriteLine("Retrieving all elements: ");
- Console.WriteLine();
- foreach(var k in key) {
- Console.WriteLine(k + ":" + ht[k]);
- }
- ArrayList al = new ArrayList(key);
- Console.WriteLine("Retrieving all keys in the arraylist");
- Console.WriteLine();
- foreach(var n in al) {
- Console.WriteLine(n);
- }
- Console.ReadKey();
- }
- }
- }