I want to use hashtable today. I need to find a good article from the Internet.ArticleTo make up for the following:
I. Hash table (Hashtable) Brief Introduction
In . NET Framework Medium, Hashtable Yes System. Collections A container provided by the namespace for processing and performance similar Key/value Key-value pairs, where Key It can be used for quick search. Key YesCase Sensitive; Value Used for storage Key . Hashtable Medium Key/value Key-value pairs are ObjectType , So Hashtable Supports any type Key/value Key-value pairs .
Ii. Simple operations on Hash Tables
Add Key/value Key-value pairs: Hashtableobject.Add(Key, value );
Remove Key/value Key-value pairs: Hashtableobject.Remove(Key );
Remove all elements from the hash table: Hashtableobject. Clear ();
Determine whether a hash table contains a specific key Key : Hashtableobject.Contains(Key );
The following ConsoleProgramAll of the above operations will be included:
using system;
using system. collections ; // use hashtable , this namespace must be introduced
class hashtable
{< br> Public static void main ()
{< br> hashtable ht = new hashtable (); /// Create A hashtable instance
ht. add ("e", "E"); /// Add key/value key-value pairs
ht. add ("A", "A");
ht. add ("C", "C");
ht. add ("B", "B");
string S = (string) HT ["A"]; // convert the object type to string
If (HT. contains ("e") // determine whether the hash table contains a specific key , the returned value is true or false
Console. writeline ("the e key: exist ");
Ht. Remove ("C ");//Remove oneKey/valueKey-value pairs
Console. writeline (HT ["A"]);//Output hereA
Ht. Clear ();// Remove all elements
Console. writeline (HT ["A"]);//There will be no output here
}
}
3. , Traverse a hash table
Used to traverse a hash table DictionaryentryObject ,CodeAs follows:
foreach (dictionaryentry de in HT) // HT for a hashtable instance
{< br> console. writeline ( de. key ); // de. key corresponds to key/value key-value pairs key
Console. writeline (De. Value);// De. KeyCorrespondsKey/valueKey-value pairsValue
}
Thu , Sort hash tables
Sort the hash table. Here we define Key/value In the key-Value Pair Key In fact, this definition cannot be implemented because we cannot directly Hashtable To Key Re-arrange, if needed Hashtable To provide the output of a rule, you can adopt a flexible approach:
Arraylist akeys = new arraylist (HT. Keys); // use a dynamic array to store all key values in hashtable.
Akeys.Sort ();//Sort in alphabetical order
Foreach (string skey in akeys)
{
Console. Write (skey + ":");
Console. writeline (HT [skey]);//Output after sorting
}