One, hash table (Hashtable) Brief
In the. NET Framework, Hashtable is a container provided by the System.Collections namespace that handles and behaves like KeyValue key-value pairs, where key is usually used for quick lookups, and key is case-sensitive; value is used to store the value corresponding to key. KeyValue Key-value pairs in Hashtable are all object types, so hashtable can support any type of KeyValue key-value pair.
Second, the simple operation of the hash table
Add a KeyValue key value pair to the hash table: Hashtableobject.add (Key,value);
Remove a KeyValue key value pair in the 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; This namespace must be introduced when using Hashtable
Class Hashtable
{
public static void Main ()
{
Hashtable ht=new Hashtable (); Create a Hashtable instance
Ht. Add ("E", "E");//adding KeyValue key-value pairs
Ht. ADD ("A", "a");
Ht. ADD ("C", "C");
Ht. ADD ("B", "B");
String s= (String) ht["A";
if (HT. Contains ("E"))//Determine if the hash table contains a specific key with a return value of TRUE or False
Console.WriteLine ("The E Key Exist");
Ht. Remove ("C");//Remove a KeyValue key-value pair
Console.WriteLine (ht["A"]);//Output a here
Ht. Clear ();//Remove all elements
Console.WriteLine (ht["A"]); There will be no output here
}
}
Third, traverse the hash table
Traversing a hash table requires the use of DictionaryEntry Object, the code is as follows:
For (KeyValuePair de in HT)//HT as a Hashtable instance
{
Console.WriteLine (DE. Key);//de. Key corresponds to the KeyValue key value pair key
Console.WriteLine (DE. Value);//de. Key corresponds to the value of the KeyValue key
}
Four, sort the hash table
Sorting the hash table here is defined as the key in the KeyValue key-value pair is rearranged by certain rules, but in practice this definition is not possible because we cannot rearrange the key directly in Hashtable, If you need hashtable to provide output for some sort of rule, you can use a workaround:
ArrayList akeys=new ArrayList (ht. Keys); Don't forget to import the System.Collections
Akeys. Sort (); Sort by alphabetical order
For (string skey in Akeys)
{
Console.Write (Skey + ":");
Console.WriteLine (Ht[skey]); Sort after output
}
Usage of Hashtable in C #