I. Brief introduction to the hash table (hashtable)
In. in the. NET Framework, hashtable is system. A container provided by the collections namespace is used to process and present key-value pairs similar to key/value. The key is usually used for quick search, and the key is case sensitive; 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 Console Program All 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 " , " A " );
Ht. Add ( " C " , " C " );
Ht. Add ( " B " , " B " );
String S = ( String ) HT [ " A " ];
If (HT. Contains ( " E " )) // Checks whether a 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, Code As follows: For (Dictionaryentry de In HT) // HT is a hashtable instance.
{
Console. writeline (De. Key );//De. Key corresponds to key/value pairs
Console. writeline (De. value );//De. Key corresponds to key/value Key-Value Pair Value
}
4. Sorting hash tables
The definition of sorting hash tables here is to re-arrange the keys in key/value pairs according to certain rules, but in fact this definition cannot be implemented, because we cannot re-arrange keys directly in hashtable, if hashtable needs to provide output of certain rules, we can adopt a work und: Arraylist akeys = New Arraylist (HT. Keys ); // Don't forget to import system. Collections
Akeys. Sort (); // Sort in alphabetical order
Foreach ( String Skey In Akeys)
{< br> console. write (skey + " : " );
console. writeline (HT [skey]); /// output after sorting
}