Working with HashTable in C# 2.0

This is a 3 part tutorial on the Hashtable class available in .NET 2.0. Part one is here and soon you will get access to the other two parts. There might be some brainstorming sessions in the last one. Please download the attached code to see the working sample. 

 

First of all Why Hashtable? The answer is very simple. Suppose you have some data that needs to be stored in a two dimensional array and have a link format of Key and Value. For example, a person name and his social security number and we can access the data using a key.

 

A close friend of Hashtable is Array (as from C/C++), it is an instance of the System.Array class, but to access data from an array you must have an index and that is of int Type. And second you must specify the size of the Array at the time of instantiations.

 

Family contains

  1. ArrayList
  2. Collection
  3. Dictionary (Hashtable or Maps)

Dictionaries or Hashtable

Are very sophisticated data structures that allow access to an element based on some key, that can be of any type.

 

Hashtable in .Net

  1. Is a member of the System.Collections namespace.
  2. Contains15 constructors ( wow, try them all) but you will mostly use.    

        Hashtable _table = new Hashtable(); //Default one

 

 

 

        Hashtable _table2 = new Hashtable(10); // capacity or size.
        Hashtable _table3 = new Hashtable(10, 06); //capacity , loadfactor

Loadfactor: this factor helps a lot if you are looking for performance. The smaller the load size (fracton of the tashtable full .6 measn 60% full) , the more efficiently our hash table works and the more memory it occupies.    

 

Now for some code:

  1. Create a Hashtable 
          

    Hashtable _simpleTable = new Hashtable();

  2. Add some data in it.
        

         _simpleTable.Add("Key1", "Value1");
    _simpleTable.Add("Key2", "Value2");

  3. Get the size.

    _simpleTable.Count; // an int value.

  4.  Now to fetch data:
  • Create an object of "IDictonaryEnumerator", this is an interface that creates an enumerator and customized for "Dictonary" objects.
        
    IDictionaryEnumerator
    _enumerator = _simpleTable.GetEnumerator();
  • while (_enumerator.MoveNext())
    {
       _string += _enumerator.Key + " "
    ;
       _string += _enumerator.Value + "\n"
    ;
    }
  • And that is all you do to fetch the data!!!
  • Clear the hash table:

    _simpleTable.Clear();
  • Search for a specific key: remember its value type when used 


    if
    (_simpleTable.ContainsKey("Key1"))
    {
        
    Console.WriteLine("Key1 is present");
    }
  • Search for a specific key: remember its value type when used


    if
    (_simpleTable.ContainsValue("Value1"))
    {
         Console.WriteLine("Value1 is present"
    );
    }
  •  Have all this done and you will get more stuff in the next article.

  •  Try this and Cheers!!!!!

Thanks
Pradeep
http://tiwaripradeep.blogspot.com/