Using Hashtables

20. September 2009 21:40

C#  Comments

Here I illustrate how to create and use hash table. Each element of hash table is a combination of Key/Value pair stored in a DictionaryEntry object. A value in a hash table can be null or contains no value but a key cannot be of null reference. Key in hash table work as an identifier for the value where you can search a hash table for a value with a specified key.

First you will need to import the namespace System.Collection. We use System.Collection namespace because it contains various interface and classes the defines various collection of objects like list, dictionary, queues, hash tables and bit arrays.

1. Adding Key/Values to Hash Table

using System;
using System.Collections;
class HashtableClass
 public static void Main()
   Hashtable htbl = new Hashtable();
   htbl.Add("AL", "Alabama");
   htbl.Add("CA", "California");
   htbl.Add("FL", "Florida");
   htbl.Add("NY", "New York");
   htbl.Add("WY", "Wyoming");
   // Get a collection of the keys.
   ICollection coll = htbl.Keys;
   foreach (string str in coll)
     Console.WriteLine(str + ": " + htbl[str]);

2. Clear all Key/Value pairs in a hash table

To clear all the key/value pairs in a hash table use Clear() method of a hash table class:


3. Remove Key/Value pairs from hash table

Just if you want to remove a particular value from a hash table use the Remove() method of hash table class and specify the Key to remove the key/value:


4. Adding Key/value pair to hash table by using indexer

We can use Add() method of the hash table class to add key/value pair to the hash table, but instead we can use indexer to add key/pair:

htbl["NY"] = "New York";

5. Use the ContainsKey() method to check if hash table contains a key

Just a simple method to use with an IF condition:

       Console.WriteLine("Hashtable contains key NY");

6. Use the ContainsValue() method to check if hash table contains a key

Just a simple method to use with an IF condition:

if(htbl.ContainsValue("New York"))
Console.WriteLine("Hashtable contains value New York");

7. Copy the keys from hash table into an array using the CopyTo() method

string[] keys=new string[5];
 No Rating