Search This Blog

Tuesday, May 17, 2016

What is Hashtable ?

Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.

A hash table is made up of a mapping function and an array. The array contains your data, while the mapping function is used to assign numerical values (keys) to the data. This helps in categorizing the data, which speeds up search times when you search for it.

using System.Collections;
using System;
class Example
{
    static void Main()
    {
                Hashtable hashtable = new Hashtable();
                hashtable [1] = "One";
                hashtable [2] = "Two";
                hashtable [3] = "Three";
                foreach (DictionaryEntry entry in hashtable)
                {
                    Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
                }
    }
}

Output:
3: Three
2: Two
1: One

HashTable Method()

using System.Collections;
using System;
class Example
{
static Hashtable GetHashtable()
    {
                // Creating a simple hashtable called hashtable.
                Hashtable hashtable = new Hashtable();
                hashtable.Add("chandra", 10);
                hashtable.Add("prakash", 11);
                hashtable.Add("vipin", 12);
                return hashtable;
   }
static void Main ()
{
Hashtable hashtable = GetHashtable ();
Console.WriteLine(hashtable.ContainsKey (“chandra”));
}

Output:

True

No comments :