C Hash Table of HashTable Usage Example Detailed Explanation of Add and Remove and Judge and Traverse and Sort etc

  • 2021-10-25 07:38:25
  • OfStack

This paper illustrates the usage of hash table (HashTable) in C #. Share it for your reference, as follows:

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. When to use a hash table

(1) Some data will be queried frequently
(2) Large amount of data
(3) Query fields contain string types
(4) The data type is not only 1

3. How to use a hash table

namespace required for hash table


using System.Collections;
using System.Collections.Generic;

Basic operations of hash table:


// Add 1 A keyvalue Key-value pair: 
HashtableObject.Add(key,value);
// Remove a keyvalue Key-value pair: 
HashtableObject.Remove(key);
// Remove all elements: 
HashtableObject.Clear();
//  Determine whether to include a specific key key : 
HashtableObject.Contains(key);

Example of console program:


using System;
using System.Collections; //file Use Hashtable You must introduce this namespace when 
class Program
{
 public static void Main()
 {
   Hashtable ht = new Hashtable(); // Create 1 A Hashtable Instances 
   ht.Add(" Beijing ", " Imperial City "); // Add keyvalue Key-value pair 
   ht.Add(" Shanghai ", " Magic Capital ");
   ht.Add(" Guangzhou ", " Provincial capitals ");
   ht.Add(" Shenzhen ", " Special zone ");
   string capital = (string)ht[" Beijing "];
   Console.WriteLine(ht.Contains(" Shanghai ")); // Determining whether the hash table contains a specific key , The return value is true Or false
   ht.Remove(" Shenzhen "); // Remove 1 A keyvalue Key-value pair 
   ht.Clear(); // Remove All Elements 
 }
}

Examples of using multiple data types in hash tables:


using System;
using System.Collections;
class Program
{
  static Hashtable GetHashtable()
  {
    Hashtable hashtable = new Hashtable();
    hashtable.Add(" Name ", " Xiaoli ");
    hashtable.Add(" Age ", 22);
    return hashtable;
  }
  static void Main()
  {
    Hashtable hashtable = GetHashtable();
    string name = (string)hashtable[" Name "];
    Console.WriteLine(name);
    int age = (int)hashtable[" Age "];
    Console.WriteLine(age);
  }
}

When retrieving data from the hash table, an InvalidCastException error occurs if the type is declared incorrectly. Use as-statements to avoid this error.


using System;
using System.Collections;
using System.IO;
class Program
{
  static void Main()
  {
  Hashtable hashtable = new Hashtable();
  hashtable.Add(100, " Xi'an ");
  //  Can be converted successfully 
  string value = hashtable[100] as string;
  if (value != null)
  {
    Console.WriteLine(value);
  }
  //  The conversion failed and the value obtained is null But no error is thrown. 
  StreamReader reader = hashtable[100] as StreamReader;
  if (reader == null)
  {
     Console.WriteLine(" Xi'an is not StreamReader Type ");
  }
  //  You can also get it directly object Value, and then make a judgment 
  object value2 = hashtable[100];
  if (value2 is string)
  {
    Console.Write(" This is a string type : ");
    Console.WriteLine(value2);
  }
  }
}

4. Traverse the hash table

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


for(DictionaryEntry 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
}

Traversal key


foreach (int key in hashtable.Keys)
{
  Console.WriteLine(key);
}

Traversal value


foreach (string value in hashtable.Values)
{
  Console.WriteLine(value);
}

5. Sort the hash table

The practice of rearranging hash tables according to key values:


ArrayList akeys=new ArrayList(ht.Keys);
akeys.Sort(); // Sort alphabetically 
foreach(string key in akeys)
{
  Console.WriteLine(key + ": " + ht[key]); // Output after sorting 
}

6. Efficiency of hash tables

The hash table under System. Collections (Hashtable) and the dictionary under System. Collections. Generic (Dictionary) can both be used as lookup table.


Stopwatch sw = new Stopwatch();
Hashtable hashtable = new Hashtable();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
int countNum = 1000000;
sw.Start();
for (int i = 0; i < countNum; i++)
{
  hashtable.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Output : 744
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  dictionary.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Output : 489
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  hashtable.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Output : 245
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  dictionary.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Output : 192

Thus, Hashtable is fast when adding data. Dictionary is fast when calling data frequently.

Conclusion: Dictionary < K,V > Is generic, and is much faster than Hashtable when K or V is a value type.

More readers interested in C # can check the topic of this site: "C # traversal algorithm and skills summary", "C # programming thread use skills summary", "C # operation Excel skills summary", "C # common control usage tutorial", "WinForm control usage summary", "C # data structure and algorithm tutorial", "C # array operation skills summary" and "C # object-oriented programming introduction tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: