1. Brief description of the hash table (hashtable)
In. NET Framework, hashtable is a container provided by the system. Collections namespace,
It is used to process and present key-value pairs similar to key/value. The key can be quickly searched, and the key is case sensitive. The value is used to store the value corresponding to the key.
In hashtable, key/value pairs are of the object type, so hashtable can support any type of key/value pairs.
Ii. Simple operations on Hash Tables
Add a key/value pair in the hash table: hashtableobject. Add (Key, value );
Remove a key/value pair in the hash table: hashtableobject. Remove (key );
Remove all elements from the hash table: hashtableobject. Clear ();
Determine whether the hash table contains the specified key: hashtableobject. Contains (key );
The following ConsoleProgramAll of the above operations will be included:
Using system;
Using system. collections; // This namespace must be introduced when hashtable is used.
Class hashtable
{
Public static void main ()
{
Hashtable ht = new hashtable (); // create a hashtable instance
Ht. Add ("e", "E"); // Add key/value pairs
Ht. Add ("A", "");
Ht. Add ("C", "C ");
Ht. Add ("B", "B ");
String S = (string) HT ["A"];
If (HT. Contains ("e") // checks whether the hash table contains a specific key. The return value is true or false.
Console. writeline ("the e key: exist ");
Ht. Remove ("C"); // remove a key/value pair
Console. writeline (HT ["A"]); // output
Ht. Clear (); // remove all elements
Console. writeline (HT ["A"]); // there will be no output here
}
}
3. traverse the hash table
Dictionaryentry object is required to traverse a hash table,CodeAs follows:
Foreach (dictionaryentry de in HT) // HT is a hashtable instance.
{
Console. writeline (De. Key); // de. Key corresponds to the key-Value Pair
Console. writeline (De. Value); // de. Key corresponds to the key/value Key-Value Pair Value
}
4. Sort hash tables
Sort the hash table. Here we define that keys in key/value pairs are reordered according to certain rules,
But in fact, this definition cannot be implemented, because we cannot directly rearrange keys in hashtable,
If hashtable is required to provide the output of certain rules, a work und can be adopted:
Arraylist akeys = new arraylist (HT. Keys); // do not forget to import system. Collections
Akeys. Sort (); // sort by letter
Foreach (string skey in akeys)
{
Console. Write (skey + ":");
Console. writeline (HT [skey]); // output after sorting
}