Name space
System.Collections
Name
Hash table (Hashtable)
Describe
A key-value pair that handles and behaves like KeyValue, where key is usually used for quick lookups, while key is case-sensitive, and value is used to store values 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
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 from the hash table
Hshtable. Contains ("Person1"); Determines whether the hash table contains the key
String name = (string) hshtable["Person1"]. ToString (); Takes the value of the specified key in the hash table
Hshtable.remove ("Person1"); Deletes the key value pair for the specified key in the hash table
IDictionaryEnumerator en = Hshtable.getenumerator (); Iterate through all the keys of the hash table and read out the corresponding values
while (en. MoveNext ())
{
String str = en. Value.tostring ();
}
The following console program will contain all of the above actions:
| 123456789Ten One A - - the - - - + - + A at - - - - - in - to + - the * $Panax Notoginseng - the + A the + - $ $ - - the -Wuyi the |
class Program { static void Main(string[] args) { // 创建一个Hashtable实例 Hashtable ht=new Hashtable(); // 添加keyvalue键值对 ht.Add("A","1"); ht.Add("B","2"); ht.Add("C","3"); ht.Add("D","4"); // 遍历哈希表 foreach (DictionaryEntry de in ht) { Console.WriteLine("Key -- {0}; Value --{1}.", de.Key, de.Value); } // 哈希表排序 ArrayList akeys=new ArrayList(ht.Keys); akeys.Sort(); foreach (string skey in akeys) { Console.WriteLine("{0, -15} {1, -15}", skey, ht[skey]); } // 判断哈希表是否包含特定键,其返回值为true或false if (ht.Contains("A")) Console.WriteLine(ht["A"]); // 给对应的键赋值 ht["A"] ="你好"; // 移除一个keyvalue键值对 ht.Remove("C"); // 遍历哈希表 foreach (DictionaryEntry de in ht) { Console.WriteLine("Key -- {0}; Value --{1}.", de.Key, de.Value); } // 移除所有元素 ht.Clear(); // 此处将不会有任何输出 Console.WriteLine(ht["A"]); Console.ReadKey(); } } |
Usage of Hashtable in C #