One, hash table (Hashtable) Brief
In the. NET framework, Hashtable is a container provided by the System.Collections namespace for handling and performing key-value pairs that resemble Key/value, where key is often used for quick lookup and key is case-sensitive ; value is used to store the value corresponding to the key. Key/value key value pairs in Hashtable are of type object, so hashtable can support any type of Key/value key-value pairs.
Second, the simple operation of a hash table
Adds a Key/value key value pair to the hash table: Hashtableobject.add (Key,value);
Removes a Key/value key value pair in a hash table: Hashtableobject.remove (key);
Remove all elements from the hash table: Hashtableobject.clear ();
Determines whether a hash table contains a specific key key:HashtableObject.Contains (key);
The following console program will contain all of the above actions:
using System;
Using System.Collections; When using Hashtable, you must introduce this namespace
class hashtable
{
public static void Main ()
{
hashtable Ht=new Hashtable (); Create a Hashtable instance
HT. Add ("E", "E");//Adds Key/value key value pair
HT. ADD ("A", "a");
HT. ADD ("C", "C");
HT. ADD ("B", "B");
String s= (String) ht["A"];
if (HT. Contains ("E"))//To determine whether a hash table contains a specific key and returns a value of True or False
Console.WriteLine ("The E key:exist");
HT. Remove ("C");/Removes a Key/value key value pair
Console.WriteLine (ht["A"]);//Output a
HT here. Clear ()//Remove all elements
Console.WriteLine (ht["A"]);//There will be no output
}
}
Three, traversing the hash table
Traversing a hash table requires the use of DictionaryEntry Object, the following code:
For (DictionaryEntry de in HT)//HT is a Hashtable instance
{
Console.WriteLine (DE. Key);//de. Key corresponds to Key/value key value pair key
Console.WriteLine (DE. Value);//de. Key corresponds to the value of the Key/value key
}
Four, sort the hash table
Sorting the hash table is defined here as Key/value the key in the value pair, but in practice this definition is not possible because we cannot rearrange the key directly in Hashtable, If you need Hashtable to provide some sort of rule output, you can use an alternative approach:
ArrayList akeys=new ArrayList (ht. Keys); Don't forget to import system.collections.
Akeys. Sort (); Sort in alphabetical order
For (string skey in Akeys)
{
Console.Write (Skey + ":");
Console.WriteLine (Ht[skey]);//Sort after output
}