Hash Tables may be familiar to many peers. it was a little strange at first, and later I got familiar with it when I used it too much. of course there are many introductions on this knowledge point on the Internet, but this does not prevent me from making my own summary and understanding.
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 can be quickly searched, and duplicate keys are not allowed, and are 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.
Therefore, you need to reference using System. Collections; the following lists common usage and the corresponding comments on the right.
I. Common Methods:
Hashtable hshTable = new Hashtable (); // create a hash table
HshTable. Add ("Person1", "zhanghf"); // Add a key-value pair to the hash table
HshTable. Clear (); // remove all key-value pairs in the hash table
HshTable. Contains ("Person1"); // determines whether the hash table Contains the key.
String name = (string) hshTable ["Person1"]. ToString (); // obtain the value of the specified key in the hash table
HshTable. Remove ("Person1"); // Delete the key-Value Pair specified in the hash table
IDictionaryEnumerator en = hshTable. GetEnumerator (); // traverses all the keys in the hash table and reads the corresponding values.
While (en. MoveNext ())
{
String str = en. Value. ToString ();
}
Ii. traverse the hash table:
DictionaryEntry Object is required to traverse a hash table. The Code is as follows:
For (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
}
Get the corresponding String Array Through the Keys and Values attributes.
ICollection keyColl = openWith. Keys;
ICollection valueColl = openWith. Values;
Iii. 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); // remember to import System. Collections
Akeys. Sort (); // calls the Sort of akeys in alphabetical order. This is easy to implement independently.
For (string skey in akeys)
{
Console. Write (skey + ":");
Console. WriteLine (ht [skey]); // output after sorting
}
Hash Tables are widely used in C # programming and have powerful functions. It is a good thing to master and be familiar with the use of hash tables!