Home > DeveloperSection > Beginner > Hashtable Class in C#

Hashtable Class in C#


C# C#  Collection 
Ratings:
0 Comment(s)
 1031  View(s)
Rate this:

Hashtable Class in C#

 

Hashtable is a collection of key/value pairs that are organized based on the hash code of the key. When elements are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. It uses key to access elements in collection. Hashtable optimizes lookups with the help of keys.

Now, we are creating a Hashtable ‘ht’ using its default constructor. The syntax are follows:

       Hashtable ht=new Hashtable ();
// adding a key and value in Hashtable
  ht.Add (“1”, “One”);//
Here ‘1’ is key and ‘One’ is value.

 

Now, we will display the element by using foreach loop. For retrieving elements through the Hashtable by using the DictionaryEntry type in a foreach loop.

foreach (DictionaryEntry e in ht)
{
  Console.WriteLine(“{0},{1}”,e.Key,e.Value);
}

 

Methods of Hashtable:

 Some important methods of Hashtable are:

1.     Add: - Adds an elements with the specified key/value in the Hashtable.

2.     Clear: - Removes all elements in the Hashtable.

3.     Contains Key: - The ContainsKey()  method returns true if key is found in hashtable otherwise, it returns false. If we want to find value are in the hashtable or not?

4.     Contains:  We use Contains () method. When, we want key/value is found or not in the Hashtable?

For checking  keys:
ht.ContainsKey(1);
For checking  Value:
int value = (int) ht[“One”]; // we need to casting as data type

 

Properties of Hashtable:-

 Some of the important properties of a Hashtable is as follows:-

1.     Keys: Gets an ICollection containing the keys in the Hashtable.

2.     Values: Gets an ICollection containing the Values in the Hashtable.

3.     Comparer: Gets or sets the IComparer to use for the Hashtable.

4.     Item: Gets or sets the values associated with the specified keys.

5.     IsReadOnly: Gets a value indicating whether the Hashtable is readonly.

 

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.

For example,

Hashtable ht= new Hashtable();
ht.Add(“10”, “Test”);
string  v = ht[40] as string;
if(v!=null)
{
  Console.WriteLine(“value is: ”+v);
}
StreamReader r= ht[10] as StreamReader
If(r!=null)
{
  Console.WriteLine(“ Reader”);
}
Object v2=ht[10];
If (v2 is string)
{
  Console.WriteLine(“Value is a string type:”+v2);
}

Output:
Value is Test
Reader
Value is a string type Test

 

If you want to store keys in arraylist: For storing keys in arraylist you can use Keys property of Hashtable. For example,

ArrayList al= new ArrayList(ht.Keys)
// For retrieving elements in the arraylist
foreach(int key in al)r
{
  Console.WriteLine(Key);
}

Advantage of Hashtable:

1.     Hashtable allows the execution time for lookup, retrieve and set operation to remain nearly constant, even for large sets.

2.     In large data sets, Hashtable is ability to locate the item quickly.

3.     No need to scan through the entire data sets to find items.

 

For example, we create an instance of Hashtable and adding four elements in it. Then we are printing all elements in the Hashtable and keys given to the arraylist for containing all keys of Hashtable and finally print it.

 

using System;
using System.Collections;
namespace HashtableEx
{
    class Program
    {
     static void Main(string[] args)
     {
        Hashtable ht = new Hashtable();
        ht.Add("1","David");
        ht.Add("2","Varun");
        ht.Add("3","Rozar");
        ht.Add("4","Farid");
     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();
        }
    }
}

 Output:



Don't want to miss updates? Please click the below button!

Follow MindStick