Using Hashtables

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.Collectionnamespace because it contains various interface and classes the defines various collection of objects like list, dictionary, queues, hash tables and bit arrays.

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]);
   }
 }
}

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:

htbl.Clear();

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:

htbl.Remove("NY");

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";

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

Just a simple method to use with an IF condition:

if(htbl.ContainsKey("NY"))
{
       Console.WriteLine("Hashtable contains key NY");
}

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");
}

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

string[] keys=new string[5];
htbl.Keys.CopyTo(keys,0);
comments powered by Disqus