Example of a hash table (HashTable) usage in C # (Add/Remove/judge/traverse/Sort etc) _c# tutorial

Source: Internet
Author: User

This example describes the use of hash tables (HashTable) in C #. Share to everyone for your reference, specific as follows:

1. Hash table (HashTable) Overview

In the. NET Framework, Hashtable is a container provided by the System.Collections namespace for handling and performing key-value pairs that resemble keyvalue, where key is often used for quick lookup, while key is case-sensitive; value is used to store values corresponding to key. KeyValue key value pairs in Hashtable are of type object, so hashtable can support any type of keyvalue key-value pairs.

2. Under what circumstances use a hash table

(1) Some data will be queried by high frequency
(2) Large amount of data
(3) Query field contains string type
(4) Data type is not unique

3. Method of use of hash table

namespace to use for a hash table

Using System.Collections;
Using System.Collections.Generic;

The basic operation of a hash table:

Add a KeyValue key value pair:
hashtableobject.add (key,value);
Remove a KeyValue key value pair:
hashtableobject.remove (key);
Remove all elements:
hashtableobject.clear ();
Determines whether a specific key is included:
hashtableobject.contains (key);

Console program Example:

Using System;
Using System.Collections; When file uses Hashtable, you must introduce this namespace
class program
{public
 static void Main ()
 {
   Hashtable ht = new Hashtable (); Create a Hashtable instance
   ht. ADD ("Beijing", "Royal Park"); Add keyvalue key value to
   ht. ADD ("Shanghai", "Magic");
   Ht. ADD ("Guangzhou", "provincial capital");
   Ht. ADD ("Shenzhen", "SAR");
   String capital = (string) ht["Beijing"];
   Console.WriteLine (HT. Contains ("Shanghai")); Determines whether a hash table contains a specific key with a return value of TRUE or False
   ht. Remove ("Shenzhen"); Removes a KeyValue key value pair
   ht. Clear (); Remove all elements
 }
}

Examples of multiple data types used in a hash table:

Using System;
Using System.Collections;
Class program
{
  static Hashtable gethashtable ()
  {
    Hashtable Hashtable = new Hashtable ();
    Hashtable. ADD ("name", "Xiaoli");
    Hashtable. ADD ("Age");
    return hashtable;
  }
  static void Main ()
  {
    Hashtable Hashtable = gethashtable ();
    String name = (string) hashtable["name"];
    Console.WriteLine (name);
    int age = (int) hashtable["ages"];
    Console.WriteLine (age);
  }


When you get the data in the hash table, a InvalidCastException error occurs if the type declaration is not correct. 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");
  able to convert
  string value = hashtable[100] As String;
  if (value!= null)
  {
    Console.WriteLine (value);
  }
  The conversion failed with a null value, but no error was thrown.
  StreamReader reader = hashtable[100] as StreamReader;
  if (reader = = null)
  {
     Console.WriteLine ("Xian is not a StreamReader type");
  }
  You can also get the object value directly, and then judge the
  object value2 = hashtable[100];
  if (value2 is string)
  {
    Console.Write ("This is a string:");
    Console.WriteLine (value2);}}


4. Traverse Hash Table

traversing a hash table requires the use of DictionaryEntry Object, the following code:

For (DictionaryEntry de in HT)//HT is a Hashtable instance
{
  Console.WriteLine (DE. Key); De. Key corresponds to the KeyValue key value pair key
  Console.WriteLine (DE. Value); De. Key corresponds to the KeyValue key value pair value
}

Traverse key

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

Traversing values

foreach (String value in Hashtable.) Values)
{
  Console.WriteLine (value);
}

5. Sort the hash table

To rearrange the hash table by key value:

ArrayList akeys=new ArrayList (ht. Keys);
Akeys. Sort (); Sort alphabetically
(string key in Akeys)
{
  Console.WriteLine (key + ": + Ht[key]); Sorted after output
}

6. Efficiency of the hash table

The System.Collections of the hash Table (Hashtable) and the System.Collections.Generic under the dictionary (Dictionary) can be used as a lookup table, which compares the execution efficiency of the two.

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

This shows that when you add data hashtable fast. Dictionary fast when you call data frequently.

Conclusion:dictionary<k,v> is generic, and when K or V is a value type, it is much faster than Hashtable.

Read more about C # Interested readers can view the site topics: "C # traversal algorithm and Skills summary", "C # Design Thread usage Tips", "C # Operation Excel Skills Summary", "C # XML file Operation Tips Summary", "C # Common control usage Tutorial", " WinForm Control Usage Summary, C # tutorial on data structure and algorithms, C # array operation techniques Summary, and C # Introduction to object-oriented Programming

I hope this article will help you with C # programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.