C # Set -- Dictionary

Source: Internet
Author: User

A dictionary is a collection in which each element is a key/value pair. A dictionary is a list commonly used for searching and sorting.

. NET Framework defines the subcode protocol through the IDictionary interface and the IDictionary <TKey, TValue> interface, and some common subcodes. Each class is different in the following aspects:

  • Whether the elements have been sorted
  • Whether the element can be obtained by index or key
  • Whether the dictionary class is generic or non-generic
  • When the field is large, the speed at which elements are retrieved based on the key value

The following table summarizes each dictionary class and their differences in the above aspects. They are an average of 5000 operations performed on a gb pc.

Type Internal Structure Indexes supported Memory usage Random insert speed (MS) Sequential insert speed (MS) Element Acquisition speed (MS) based on the key)
Unordered dictionary            
Dictionary <T, V> Hash table No 22 30 30 20
Hashtable Hash table No 38 50 50 30
ListDictionary Linked List No 36 50000 50000 50000
OrderedDictionary Hash table
+ Array
Yes 59 70 70 40
Sort dictionary            
SortedDictionary <K, V> Red/black tree No 20 130 100 120
SortedList <K, V> 2 xArray Yes 20 3300 30 40
SortList 2 xArray Yes 27 4500 100 180

In terms of time complexity, it takes the following time to obtain values from the dictionary using keys:

  • The time complexity of Hashtable, Dictionary, and OrderedDictionary is O (1)
  • The time complexity of SortedDictionary and SortList is O (logN)
  • The time complexity of ListDictinary is O (n)

N is the number of set elements.

 

IDictionary <TKey, TValue>

IDictionary <TKey, Tvalue> specifies all standard protocols based on key/value sets. Because it adds methods and attributes to read elements through keys, it extends the ICollection <T> interface:

  IDictionary <TKey, TValue><KeyValuePair <TKey, TValue>> TryGetValue (TKey key,  [TKey key] { ; ; } ICollection <TKey> Keys { ; } ICollection <TValue> Values { ; } }

To add an element to the dictionary, you can call the add method or use the set method of the indexer. For the latter, if the key of the element to be added does not exist in the field, insert the element into the dictionary; otherwise, the value corresponding to the same key in the dictionary is updated. Duplicate keys are not accepted for all dictionary implementation classes. Therefore, if the same key is used when the add method is called twice, an exception is thrown.

To obtain an element from a field, you can use the get method of the indexer or call the TryGetValue method. If the key does not exist, the indexer method throws an exception, while TryGetValue returns false. You can use the ContainsKey method to check whether a key exists in the dictionary. However, this causes additional query overhead.

You can use the KeyValuePari structure to traverse IDictionary <TKey, TValue>.

  KeyValuePair<TKey, TValue>.key =.value = {  {   =( Key != ( Value != 

Of course, you can also use the dictionary's Keys or Values attribute to traverse all Keys or Values of the dictionary. The Dictionary class demonstrates how this interface is used.

 

 

IDictionary

IDictionary is a non-generic dictionary interface. It is different from IDictionary <TKey, TValue>:

     Object                      

Use the DictionaryEntry interface to traverse non-generic dictionaries

     ====

 

Dictionary <TKey, TValue> and Hashtable

The Dictionary class of geneirc is the most commonly used collection class (In addition, it is the List <T> collection class ). Dictionary <TKey, TValue> uses the hash data structure to store keys and values. Therefore, it is fast and efficient.

A non-generic Dictionary <TKey, TValue> is Hashtable; therefore, there is no non-generic class Dictionary. When we mention Dictionary, we generally refer to Dictionary <TKey, TValue>.

Dictionary implements the IDictionary interface of generic and non-generic. The IDictonary of generic is exposed to public. In fact, Dictionary generally implements the IDictionary interface of generic.

The following code demonstrates how to use the Ditionary <TKey, TValue> class:

 d =  Dictionary<, >, ] = ; d[] = ; d[] = ]); Console.WriteLine (d.ContainsKey ()); Console.WriteLine (d.ContainsValue ());  val =  (!d.TryGetValue (, );  (KeyValuePair<, > kv  d) Console.WriteLine (kv.Key +  + kv.Value);  ( s  d.Keys) Console.Write (s);  ( i  d.Values) Console.Write (i); 

The hash table behind this class converts each key into an integer Hash code, and then converts it into a hash key through algorithms. Internally, use the hash key to determine which bucket a member belongs to. If a bucket contains multiple values, perform a linear search for the bucket. A good hash algorithm not only attempts to return a strict hash code, but also implements a uniform distribution of the returned hash codes in 32-bit integers.

The dictionary can contain any type of keys, as long as these keys support equal interfaces and can obtain hash codes. By default, key equality depends on the Equals method of the object, and the algorithm for calculating the hash key is also based on the GetHashCode method of the object. These actions are not static. If the Equals method or GetHashCode method is overloaded, or the IEqualityComparer instance object is provided when the dictionary instance is created. A common application is to provide case-sensitive equality comparator instances when using string fields.

 d =  Dictionary<, > (StringComparer.OrdinalIgnoreCase);

Like other collection types, if the field size is specified when the dictionary instance is constructed, the performance can be improved to a certain extent. Specify the dictionary size to avoid or reduce the size of the dictionary.

The disadvantage of Dictioanry and Hashtable is that items is not sorted. Even the members added to the dictionary do not retain the original sequence. In addition, the dictionary does not receive duplicate keys.

 

OrderedDictionary

OrderedDictionary is a non-generic dictionary class that stores the original sequence of members. When OrderedDictioanry is used, you can obtain field elements through indexes or keys.

OrderedDictionary combines Hashtable and ArrayList. This means that it has not only all Hashtable functions, but also RemoveAt and integer indexer methods. It also exposes the Keys and Values attributes based on the original order of the elements.

This class is introduced in. NET 2.0, and there is no corresponding non-generic version.

 

ListDictionary and HybirdDictionary

ListDictionary uses a single-chain table to store data. It does not provide sorting, although it retains the original order of elements. When the set is large, its performance is quite low. It is worth noting that it is only effective when the number of elements is very small (less than 10 elements ).

HybirdDictionary is a ListDictionary. It is automatically converted to Hashtable when the number of elements reaches a certain value to solve the performance problem of ListDictionary. This idea can enable low memory usage when there are few dictionary elements, while a large number of dictionaries have better performance. However, after a certain amount of data is reached, it is necessary to convert from one data type to another -- and Dictionary is not too slow or performance low in both cases -- therefore, why didn't you start using the Dicontary class.

In addition, both classes are non-generic classes.

 

Sorted Dictionary

Framework provides two dictionary classes, which are constructed by the sort key. These two classes are SortedDictoanry <TKey, TValue> and SortedList <Tkey, TValue>.

SortedDictoanry <TKey, TValue>, uses a red/black tree: a data structure that ensures that any insert or retrieve element behavior is consistent.

SortedList <Tkey, TValue> is implemented by an array pair after sorting, which can be quickly read, but the insertion performance is poor.

 

SortedDictoanry <TKey, TValue> is faster than SortedList and inserts elements in random order. SortedList has an additional function that can be used to obtain elements through indexes or keys. By using the sorted list, you can find the first few elements. If you want to achieve the same purpose in SortedDictionary, You need to traverse n elements manually.

 

The following example demonstrates how to use reflection to load all the System. Object classes to a sorted list, and then traverse the keys and values of the list.

 sorted =  SortedList <, MethodInfo> (MethodInfo m   (= ( name  (MethodInfo m +  + m.ReturnType);

The result of the first list is as follows:

Equals
GetHashCode
GetType
ReferenceEquals
ToString

The result of the second list is as follows:

Equals returns a System. Boolean
GetHashCode returns a System. Int32
GetType returns a System. Type
ReferenceEquals returns a System. Boolean
ToString returns a System. String

Please note that we use the indexer to fill in the field class. If we use the add method, an exception will be thrown because the object class on which we depend is overloaded with the Equals method, and you cannot add duplicate keys to a dictionary. Using the indexer will avoid this problem.

If we extend our example, the following code will return the GetHashCode method, which is used in the same way as a common dictionary.

Console.WriteLine (sorted []);
Up to now, our Code applies to both SortedDictionary and SortedList. However, the following two lines of code only apply to SortedList
Console.WriteLine (sorted.Keys [sorted.Count - ]); Console.WriteLine (sorted.Values[sorted.Count - ].IsVirtual); 

Related Article

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.