C # HashTable using the usage explanation

Source: Internet
Author: User

 

How does the Hashtable class work in C #? This article will give you an answer to the hash table (Hashtable) outlined in the. NET Framework,

One, Hashtable is a container provided by the System.Collections namespace that handles and behaves like KeyValue key-value pairs, where key is usually used for quick lookups, while key is case-sensitive; value is used to store the value 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 Hashtable adds a KeyValue key value pair to the hash table: Hashtableobject.add (Key,value);

Remove a KeyValue key value pair in the hash table: Hashtableobject.remove (key);

Remove all elements from the hash table: Hashtableobject.clear ();

Determines whether a hash table contains a specific key key:HashtableObject.Contains (key);

The following console program will contain all of the above actions:

Using System;

Using System.Collections; When file uses Hashtable, this namespace must be introduced

Class Hashtable

{

public static void Main ()

{

Hashtable ht=new Hashtable (); File creates a Hashtable instance

Ht. Add (e,e); adding keyvalue key-value pairs

Ht. ADD (A,a);

Ht. ADD (C,C);

Ht.   ADD (B,B); String s= (String) ht[a];

if (HT. Contains (E)) file determines whether a hash table contains a specific key with a return value of TRUE or False

Console.WriteLine (the E keyexist);

Ht. Remove (C) removes a keyvalue key-value pair

Console.WriteLine (Ht[a]); here output A

Ht. Clear (); Remove all elements

Console.WriteLine (Ht[a]); File will not have any output here

}

}

Third, traversing the hash table traversing the hash table requires the use of DictionaryEntry Object, the code is as follows:

For (DictionaryEntry de in HT) fileht as a Hashtable instance

{

Console.WriteLine (DE. Key);d E. Key corresponds to the KeyValue key value pair key

Console.WriteLine (DE. Value);d E. Key corresponds to the value of the KeyValue key

}

Four, sort the hash table sort the hash table. The definition here is to rearrange the keys in the KeyValue key-value pair according to certain rules, but in practice this definition is not possible because we cannot rearrange the keys directly in Hashtable, If you need hashtable to provide output for some sort of rule, you can use a workaround:

ArrayList akeys=new ArrayList (ht. Keys); File don't forget to import the System.Collections

Akeys. Sort (); File is sorted in alphabetical order

For (string skey in Akeys)

{

Console.Write (Skey +);

Console.WriteLine (Ht[skey]); Sort after output

}


  I. INTRODUCTION

Represents a collection of key/value pairs that are organized according to the hash code of the key.

Provides quick queries. The storage of elements is independent of order. The element cannot be inserted at the specified location because it does not have a valid sort by itself. Feel that its advantages are reflected in the query.

The Hashtable key must be unique, without a valid sort, and it carries the inner sort

public class Hashtable:idictionary, ICollection, IEnumerable,

ISerializable, Ideserializationcallback, ICloneable

Each element is a key/value pair stored in the DictionaryEntry object. The key cannot be a null reference (Nothing in Visual Basic), but the value is OK.

Note: The so-called dictionaryentry structure is defined as a dictionary key-value pair that can be set or retrieved, with a key property, a Value property that represents the key and the value, respectively

 Two. Add

Hashtable.add method

public virtual void Add (

Object Key,

Object value

);

Adds an element with the specified key and value to the Hashtable.

Key of the element to add.

Value of the element to add. The value can be a null reference (Nothing in Visual Basic).

The Item property can also be used to add a new element by setting the value of a key that does not exist in Hashtable. For example: mycollection["myNonexistentKey"] = myvalue. However, if the specified key already exists in Hashtable, setting the Item property overwrites the old value. In contrast, the Add method does not modify existing elements.

Hashtable htable = new Hashtable ();

Htable.add ("1", "a");

Htable.add ("2", "B");

Htable.add ("3", "C");

Htable.add ("4", "D");

Htable.add ("5", "E");

Htable.add ("1", "aaaaaaaaaaa"); Error because there is already a key "1"

htable["1"] = "aaaaaaaaaaa"; Ok

Dropdownlist2.datasource = htable;

Dropdownlist2.datatextfield = "Key";

Dropdownlist2.datavaluefield = "Value";

Dropdownlist2.databind ();

 Two. Delete

1. public virtual void Remove (

Object key

);

Removes the element with the specified key from the Hashtable.

If the Hashtable does not contain an element with the specified key, the Hashtable remains unchanged. No exception is thrown.

2. public virtual void Clear ();

Removes all elements from the Hashtable.

Count is set to zero. The capacity remains the same.

Three. Other

1. Public virtual ICollection Values {get;}

Gets the ICollection that contains the value in Hashtable.

Note: The ICollection interface defines the size, enumerator, and synchronization methods for all collections.

Hashtable htable = new Hashtable ();

Htable.add ("1", "a");

Htable.add ("2", "B");

Htable.add ("3", "C");

Htable.add ("4", "D");

Htable.add ("5", "E");

Label2.Text = "";

foreach (String strkey in Htable.keys)//traversal

{

Label2.Text + = strkey;

Label2.Text + = ",";

}

2. Public virtual ICollection Keys {get;}

Gets the ICollection that contains the keys in the Hashtable.

The returned ICollection is not a static copy; instead, ICollection references the keys in the original Hashtable.


As a result, changes to Hashtable continue to be reflected in the ICollection.

3. Public virtual bool Contains (

Object key

);

Determines whether the Hashtable contains a specific key.

4. Public virtual bool ContainsKey (

Object key

);

Determines whether the Hashtable contains a specific key. Same as contains

5. Public virtual bool Containsvalue (

Object value

);

Determine if Hashtable contains a specific value

6. public virtual int Count {get;}

Gets the number of key-value pairs contained in the Hashtable

C # Collection Series ~hashtable usage

Hash table, name-value pair. Similar to dictionaries (more powerful than arrays). The hash table is optimized, and the object that accesses the subscript is hashed first.

If the element is accessed with any type of key value, it is faster than the other collection. The GetHashCode () method returns an int type of data,

Use the value of this key to generate the int type data. Hash table gets this value finally returns an index that represents the number with the given hash

The location that the item is stored in the dictionary. In the. NET Framework, Hashtable is the System.Collections namespace

Provides a container for handling and performing key-value pairs similar to KeyValue, where key is usually used for quick lookups, while key

is case-sensitive; value is used to store values corresponding to key. The KeyValue key-value pairs in Hashtable are all object types,

So Hashtable can support any type of KeyValue key-value pair.

1. Before using Hashtable. You need to add a system.collections reference

2. Adding elements

Hashtable HT =new Hashtable ();

Ht. ADD (Key,value);//Key,value can be any type

If the key has a repetition will throw a run-time exception, you can handle

if (HT. Contains (key) ==false)

{ht. Add (key,value);//Added} if not present

It can be done this way, and it's much more efficient.

Try

{

Ht. ADD (Key,value);

}

Catch

{//Do not handle duplicate exceptions}

3. Deleting an element

Ht. Remove (key);

4. Delete all

Ht. Clear ();

5. Determine if the key already exists

Ht. Contains (key)//This has just been used.

6. Traversal key

foreach (Object key in Ht. Keys)

{}

7. Traversing values

foreach (Object value in HT. Values)

{}

8. Simultaneous traversal of key-value pairs

foreach (DictionaryEntry de in HT)

{

Console.WriteLine (DE. key);//Get Key

Console.WriteLine (DE. value);//Get values

}

9. Sort output (same as for values)

ArrayList Akeys = new ArrayList (HT. Keys);

Akeys. Sort ();

Example:

Creates and initializes a new Hashtable.

Hashtable myht = new Hashtable ();

Myht.add ("One", "the");

Myht.add ("Both", "quick");

Myht.add ("Three", "Brown");

Myht.add ("Four", "Fox");

Displays the Hashtable.

Console.WriteLine ("The Hashtable contains the following:");

Printkeysandvalues (MYHT);

}

public static void Printkeysandvalues (Hashtable myht)

{

foreach (string s in Myht.keys)

Console.WriteLine (s);

Console.WriteLine ("-key--value-");

foreach (DictionaryEntry de in Myht)

Console.WriteLine ("{0}: {1}", DE. Key, DE. Value);

Console.WriteLine ();

}

C # HashTable using the usage explanation

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.