English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C# Hashtable (Hash Table)
HashTable Features
Hashtable stores key-value pairs.
Belongs to the System.Collection namespace.
Implements the IDictionary interface.
Keys must be unique and cannot be null.
Values can be null or duplicated.
Elements are stored as DictionaryEntry objects.
The following example demonstrates how to create a hash table and add elements.
Hashtable numberNames = new Hashtable(); numberNames.Add(1, "One"); //Add keys using the Add() method/Value numberNames.Add(2, "Two"); numberNames.Add(3, "Three"); //The following causes a runtime exception: The key has already been added. run-time exception: key already added. //numberNames.Add(3, "Three"); foreach(DictionaryEntry de in numberNames) Console.WriteLine("Key: {0}, Value: {"1}" //Using a collection-initializer syntax to create a Hashtable var cities = new Hashtable(){ {"UK", "London, Manchester, Birmingham"}, {"USA", "Chicago, New York, Washington"}, {"India", "Mumbai, New Delhi, Pune"} } foreach(DictionaryEntry de in cities) Console.WriteLine("Key: {0}, Value: {"1}"
The Hashtable collection can include all elements of a dictionary, as shown below.
Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); dict.Add(2, "two"); dict.Add(3, "three"); Hashtable ht = new Hashtable(dict);
By passing a key to the indexer, you can retrieve the value of an existing key from the Hashtable. Since Hashtable is a non-generic collection, a value type must be typed when retrieving it.
//Using a collection-initializer syntax to create a Hashtable var cities = new Hashtable(){ {"UK", "London, Manchester, Birmingham"}, {"USA", "Chicago, New York, Washington"}, {"India", "Mumbai, New Delhi, Pune"} } string citiesOfUK = (string) cities["UK"]; //Convert to string string citiesOfUSA = (string) cities["USA"]; //Convert to string Console.WriteLine(citiesOfUK); Console.WriteLine(citiesOfUSA); cities["UK"] = "Liverpool, Bristol"; // Update the value of UK cities["USA"] = "Los Angeles, Boston"; //Update the value of USA if(!cities.ContainsKey("France")){ cities["France"] = "Paris"; }
The Remove() method deletes the key-value pair that matches the specified value in the Hashtable. If the specified key is not found in the Hashtable, a KeyNotFoundException is thrown, so the ContainsKey() method is used to check for the existing key before deletion.
The Clear() method can delete all elements at once.
var cities = new Hashtable(){ {"UK", "London, Manchester, Birmingham"}, {"USA", "Chicago, New York, Washington"}, {"India", "Mumbai, New Delhi, Pune"} } cities.Remove("UK"); // Remove UK //Remove UK //Throw a runtime exception: KeyNotFoundException if(cities.ContainsKey("France")){ // Check before retrieving the key Remove UK } cities.Clear(); //Remove All Elements
The following figure illustrates the hierarchy of the Hashtable class.