Explain the usage of HashTable in C in detail

  • 2021-09-11 20:58:18
  • OfStack

1. Brief introduction of hash table (Hashtable)

In. NET Framework, Hashtable is a container provided by System. Collections namespace, which is used to process and represent key-value pairs similar to keyvalue, where key can usually be used for quick lookup, while key is case sensitive; value is used to store a value corresponding to key. keyvalue key-value pairs in Hashtable are all of object type, so Hashtable can support any type of keyvalue key-value pairs.

2. Simple operation of hash table

Add an keyvalue key value pair to the hash table: HashtableObject. Add (key, value);
Removing an keyvalue key-value pair from the hash table: HashtableObject. Remove (key);
Remove all elements from the hash table: HashtableObject. Clear ();
Determining whether the hash table contains a specific key key: HashtableObject. Contains (key);

The following console program will contain all the above operations:


using System;
using System.Collections; // Use Hashtable You must introduce this namespace when 
class hashtable
{
public static void Main()
{
Hashtable ht=new Hashtable(); // Create 1 A Hashtable Instances 
ht.Add("E","e");// Add keyvalue Key-value pair 
ht.Add("A","a");
ht.Add("C","c");
ht.Add("B","b");
string s=(string)ht["A"];
if(ht.Contains("E")) // Determining whether the hash table contains a specific key , The return value is true Or false
Console.WriteLine("the E key exist");
ht.Remove("C");// Remove 1 A keyvalue Key-value pair 
Console.WriteLine(ht["A"]);// Output here a
ht.Clear();// Remove All Elements 
Console.WriteLine(ht["A"]); // There will be no output here 
}
}

3. Traverse the hash table

Traversing the hash table requires DictionaryEntry Object with the following code:


for(KeyValuePair de in ht) //ht For 1 A Hashtable Instances 
{
Console.WriteLine(de.Key);//de.Key Corresponds to keyvalue Key-value pair key
Console.WriteLine(de.Value);//de.Key Corresponds to keyvalue Key-value pair value
}

4. Sort the hash table

The definition of sorting hash table here is to rearrange key in keyvalue key-value pair according to 1 rule, but in fact this definition cannot be realized because we cannot rearrange key directly in Hashtable. If Hashtable is required to provide some rule output, one workaround can be adopted:


ArrayList akeys=new ArrayList(ht.Keys); // Don't forget to import System.Collections
akeys.Sort(); // Sort alphabetically 
for(string skey in akeys)
{
Console.Write(skey + ":");
Console.WriteLine(ht[skey]); Output after sorting 
}

The above is the site to introduce the use of HashTable in C #, I hope to help you!


Related articles: