Monday, September 20, 2010

Working with Hashtable


Working with Hashtable:
HashTable class is one of the effective collection classes available in the Sytsem.Collections namespace. Out of all available classes ArrayList and Hashtable are used more frequently. Apart from all the collection classes Hastable has got one additional feature, i.e., it allows to store the element with a unique key value. Hashtable allows to store the elements as key value pairs. Hastable organize the element based on the hash code of the key.
Common Methods used in Hashtable:
Add():
Is used to add elements to the Hashtable, with a unique key as follows. We can assign the productid with collections of products.
Insert elements into  Hashtable:
Hashtable Products = new Hashtable();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Remove():
Is used to remove the element with specified key from the hashtable.
   Hashtable Products = new Hashtable();
   Products.Add("FT", "FM Transmitter");
   Products.Add("DC", "DJCable");
   Products.Add("Ad", "Power Adapter");
   Console.WriteLine("Before the element is removed");
            foreach (DictionaryEntry s in Products)
            {
                Console.WriteLine("Product ID:{0}\t Product Name:{1}", s.Key,s.Value);
            }
   Products.Remove("Ad");
   Console.WriteLine("====================");
   Console.WriteLine("After the element is removed");
   foreach (DictionaryEntry s in Products)
            {
                Console.WriteLine("Product ID:{0}\t Product Name:{1}", s.Key, s.Value);
            }
Contains() and Containskey():
Returns a boolean value which is used to determine whether the hashtable contains the specified key.
Hashtable Products = new Hashtable();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Console.WriteLine("{0}",Products.Contains("Ad"));            Console.WriteLine("{0}", Products.ContainsKey("Ad"));

ContainsValue():
Returns a boolean value which is used to determine whether the hashtable contains the specified value.
Hashtable Products = new Hashtable();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Console.WriteLine("{0}", Products.ContainsValue("DJCable"));

CopyTo():
Is used to copies entire elements in the Hashtable to an existing one dimensional array.
string[ ] products = new string[ 3 ];
Hashtable Products = new Hashtable();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Products.CopyTo(products, 0);
foreach (string s in products)
    {
       Console.WriteLine("{0}", s);
    }

Next:
Working with Generics.

Furhter Reading: 
Hashtable

No comments:

Post a Comment