Apply a hashtable in C # (Hashtable)

xiaoxiao2021-03-06  109

First, the hashtable (Hashtable)

In .NET Framework, HashTable is a container provided by the System.Collections namespace for processing and expressing key-value pairs like Key / Value, where KEY is usually available, while Key is case sensitive; VALUE is used for Store values ​​corresponding to Key. The key / value key value in HashTable is an Object type, so HashTable can support any type of Key / Value key value pair.

Second, the bricked table of the hash table adds a Key / Value key value in the hash table: HashTableObject.add (key, value); removes a Key / Value key value in the hash table: HashtableObject.remove Key); removes all elements from the hash table: HashTableObject.clear (); Judging whether the hash table contains a specific key Key: HashTableObject.contains (key); the following console will contain all the above operations: use system; using When using hashtable, you must introduce this namespace Class HashTable {public static void main () {uShtable HT = new hashtable (); // Create a HashTable instance HT.Add ("e", "e" ); // Add Key / Value key value to ht.add ("a", "a"); HT.Add ("c", "c"); ht.add ("b", "b"); String s = (string) HT ["a"]; if (HT.Contains ("E")) // Judging whether the hash table contains a specific key, its return value is true or falseconsole.writeline ("The e key: EXIST "); ht.remove (" c "); // Remove a key / value key value to console.writeLine (HT [" A "]); // outputs AHT.CLEAR () here; // In addition to all elements console.writeline (HT ["A"]); // will not have any output}}}}}

Third, traversing the hash table, traversing the hash table, you need to use the DictionaryEntry Object, the code is as follows: for (DictionaryTry de in HT) // HT is a HashTable instance {console.writeline (de.key); // de.key corresponds to Key / Value key value to KeyConsole.writeline (de.value); // de.key corresponds to the key / value key value pair value}

4. Sort the hash table to the hash table is defined here. The key to the key / value key value is rearranged, but in fact, this definition cannot be implemented, because we can't be directly HashTable rearranges the key, if you need HashTable to provide the output of a certain rule, you can use a variety of ways: arraylist akeys = new arraylist (ht.keys); // Don't forget to import system.collectionsakeys.sort () ; // alphabetically sorted for (string skey in akeys) {Console.Write (skey ":"); Console.WriteLine (ht [skey]);} // after the sort of output: kwklover

转载请注明原文地址:https://www.9cbs.com/read-102652.html

New Post(0)