Hashtable dictionary [mandatory]

Source: Internet
Author: User
1: hashtable is recommended in multi-threaded programs. The default hashtable allows single-threaded writing and multi-threaded reading. For hashtable, the synchronized () method can be further called to obtain a completely thread-safe type. dictionary is NOT thread-safe and must be manually protected using the lock statement, greatly reducing the efficiency.

2: dictionary is recommended in a single-threaded program. It has the advantage of generics, fast reading speed, and sufficient capacity utilization.
3: dictionary has the ability to sort data by insertion Order (Note: however, when the remove () function is called to delete a node, the order is disrupted ), therefore, it is convenient to use a dictionary to reflect the order.

 

Hashtable class and dictionary <(of <(tkey, tvalue>) generic class implement idictionary Interface

Dictionary <(of <(tkey, tvalue>) generic classes also implement idictionary <(of <(tkey, tvalue>) Generic interfaces. Therefore, each element in these sets is a key/value pair.

Dictionary <(of <(tkey, tvalue>) has the same functions as hashtable.
For value types, the performance of the Dictionary of a specific type (excluding objects) <(of <(tkey, tvalue>)> is better than that of hashtable, because the hashtable element belongs to the object type, therefore, the packing and unboxing operations are often triggered when the value type is stored or retrieved.

Hashtableht = new hashtable (); // implement the idictionary Interface
Ht. Add (1, "");
Ht. Add (2, "B ");
Ht. Add (3, "C ");
Foreach (dictionaryentry de in HT) // hashtable returns the dictionaryentry type
{
De. Key;
De. value;
}

Dictionary <int, string> mydictionary = new dictionary <int, string> (); // implements the idictionary interface and the idictionary <t key, T value> class.
Mydictionary. Add (1, "");
Mydictionary. Add (2, "B ");
Mydictionary. Add (3, "C ");
Foreach (int I in mydictionary. Keys)
{
Console. writeline ("Key =" + I + "value =" + mydictionary );
}
Or
Foreach (keyvaluepair <string, double> temp in mydictionary) // The returned keyvaluepair <string, double> Generic Array
{
Temp. Key;
Temp. value;
}

The most common use of generics is the generic set, namespace system. collections. generic contains some generic-based collection classes. Using generic collection classes can provide higher type security and higher performance, avoiding repeated packing and unpacking of non-generic sets.
Many non-generic collection classes have their corresponding generic collection classes. Below are common non-generic collection classes and their generic collection classes:
Non-generic collection class
Arraylist list <t>
Hashtable dictionary <t>
Queue queue <t>
Stack stack <t>
Sortedlist <t>

Many non-generic collection classes we use mainly include the arraylist class and the hashtable class. We often use hashtable to store the information to be written to or returned to the database. In this case, we need to constantly convert the data types, increasing the burden of system packing and unpacking, it is much easier to store data using the dictionary <tkey, tvalue> collection class if the data types we manipulate are relatively fixed, for example, you can use dictionary <string, int> to store your shopping cart information (product name, number of items) on an e-commerce website, without any type conversion.

The following is a simple example, including declarations, filling in key-value pairs, removing key-value pairs, and traversing key-value pairs.

Dictionary <string, string> mydic = new dictionary <string, string> ();
Mydic. Add ("AAA", "111 ");
Mydic. Add ("BBB", "222 ");
MySQL. Add ("CCC", "333 ");
Mydic. Add ("DDD", "444 ");
// If an existing key is added, the add method throws an exception.
Try
{
Mydic. Add ("DDD", "DDD ");
}
Catch (argumentexception ex)
{
Console. writeline ("this key already exists:" + ex. Message );
}
// The Method for Solving the add () exception is to use the containskey () method to determine whether the key exists.
If (! Mydic. containskey ("DDD "))
{
Mydic. Add ("DDD", "DDD ");
}
Else
{
Console. writeline ("this key already exists :");

}

// When the index is used as a negative value, if the value already exists, the key value of the existing key will be modified without throwing an exception.
Mydic ["DDD"] = "DDD ";
Mydic ["eee"] = "555 ";

// An exception occurs if the key does not exist when you use the indexer.
Try
{
Console. writeline ("nonexistent key" "fff" "has the following key values:" + mydic ["fff"]);
}
Catch (keynotfoundexception ex)
{
Console. writeline ("the key is not found and an exception is thrown:" + ex. Message );
}
// The method to solve the above exception is to use contarnskey () to determine if a key exists. If you need to calculate the key value frequently, it is best to use trygetvalue to obtain the corresponding key value in the set.
String value = "";
If (mydic. trygetvalue ("fff", out value ))
{
Console. writeline ("nonexistent key" "fff" "has the following key values:" + value );
}
Else
{
Console. writeline ("the corresponding key value is not found ");
}

// Use foreach below to Traverse Key-value pairs
// The generic struct is used to store the key-value pair.
Foreach (keyvaluepair <string, string> kVp in mydic)
{
Console. writeline ("Key = {0}, value = {1}", kVp. Key, kVp. value );
}
// Obtain a set of values
Foreach (string s in mydic. values)
{
Console. writeline ("value = {0}", S );
}
// Another method is worth obtaining
Dictionary <string, string>. valuecollection values = mydic. values;
Foreach (string s in values)
{
Console. writeline ("value = {0}", S );
}
Common attributes and methods are as follows: common attributes
Attribute description
 
Comparer
Obtain the iequalitycomparer used to determine whether the keys in the dictionary are equal.
 
Count
Obtains the number of key/value pairs contained in a dictionary.
 
Item
Gets or sets the value associated with the specified key.
 
Keys
Obtains a set of keys in a dictionary.
 
Values
Obtains a set of values in a dictionary.
 
Common Methods
Add
Adds the specified key and value to the dictionary.
 
Clear
Remove all keys and values from dictionary.
 

Containskey
Determines whether a dictionary contains the specified key.
 
Containsvalue
Determines whether a dictionary contains a specific value.
 
Equals
Overloaded. Determine whether the two object instances are equal. (Inherit from object .)
 
Getenumerator
Returns the number of enumerations that access the dictionary cyclically.
 
Gethashcode
Used as a hash function of a specific type. Gethashcode is applicable to hash algorithms and data structures (such as hash tables. (Inherit from object .)
 
Getobjectdata
Implement the system. runtime. serialization. iserializable interface and return the data required to serialize the dictionary instance.
 
GetType
Obtain the type of the current instance. (Inherit from object .)
 
Ondeserialization
Implement the system. runtime. serialization. iserializable interface and trigger a deserialization event after deserialization.
 
Referenceequals
Determine whether the specified object instance is the same. (Inherit from object .)
 
Remove
Removes the value of the specified key from dictionary.
 
Tostring
Returns the string of the current object. (Inherit from object .)
 
Trygetvalue
Obtains the value associated with the specified key.

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.