C # Generic collection of dictionary<k, v> usage tips

Source: Internet
Author: User

  1. 1. To use the dictionary collection, you need to import the C # generic namespace
  2. System.Collections.Generic (assembly: mscorlib)
  3. 2. Description
  4. 1), a mapping from a set of keys (key) to a set of values (value), each of which is made up of a value and its associated key
  5. 2), any key must be unique
  6. 3), the key cannot be null reference null (Nothing in VB), if the value is a reference type, it can be a null value
  7. 4), key and value can be of any type (string,Int,custom class, etc.)
  8. 3. Create and initialize
  9. dictionary<int, string> mydictionary = new dictionary<int, string> ();
  10. 4. Adding elements
  11. Mydictionary.add ("C #", 0);
  12. Mydictionary.add ("C + +", 1);
  13. Mydictionary.add ("C", 2);
  14. Mydictionary.add ("VB", 2);
  15. 5. Find element by Key
  16.   if (Mydictionary.containskey ("C #"))
  17. {
  18. Console.WriteLine ("Key:{0},value:{1}", "C #", mydictionary["C #"]);
  19. }
  20. 6. Traverse element by KeyValuePair
  21.   foreach (keyvaluepair<string, int> kvp in mydictionary)
  22. {
  23. Console.WriteLine ("Key = {0}, Value = {1}", kvp. Key, kvp. Value);
  24. }
  25. 7. Traverse key by Keys property only
  26. dictionary<string, int>. KeyCollection keycol = Mydictionary.keys;
  27.   foreach (string key in keycol/*string key in mydictionary.keys*/)
  28. {
  29. Console.WriteLine ("key = {0}", key);
  30. }
  31. 8. Traverse only the value by Valus property
  32. dictionary<string, int>. ValueCollection valuecol = mydictionary.values;
  33.   foreach (int value in valuecol)
  34. {
  35. Console.WriteLine ("value = {0}", value);
  36. }
  37. 9. Removing the specified key value by the Remove method
  38. Mydictionary.remove ("C #");
  39.   if (Mydictionary.containskey ("C #"))
  40. {
  41. Console.WriteLine ("Key:{0},value:{1}", "C #", mydictionary["C #"]);
  42. }
  43.   Else
  44. {
  45. Console.WriteLine ("non-existent key:c#");
  46. }
  47. In the System.Collections.Generic namespace, the generic set corresponding to the ArrayList is List<t>, and the generic collection corresponding to the Hashtable is dictionary<k,v> It stores data in a way that is similar to a hash table, holds elements by key/value, has all the characteristics of generics, checks type constraints at compile time, and does not require type conversions when reading.
  48. Phone Book storage example, using dictionary<k,v> to store the telephone information, the code is as follows:
  49. dictionary<string,telnote> ht=new dictionary<string,telnote> ();
  50. In the dictionary<k,v> declaration,string in "< String,telnote>" represents the type of key in the collection, Telnote represents the type of value, and the definition dictionary The methods in the <K,V> generic collection are as follows:
  51. dictionary<k,v> students=New dictionary<k,v> ();
  52. where "K" is a placeholder, specifically defined with the storage key "key" of the data type instead, "V" is also a placeholder, with the value of the element "value" of the data type instead, so that when the collection is defined, the data type of the key and value of the stored element is declared, guaranteeing the type of security.
  53. The elements in dictionary<k,v> are similar to Hashtable, adding elements, getting elements, deleting elements, and iterating through the elements of the collection basically the same way.
  54. The difference between dictionary<k,v> and Hashtable
  55. Dictionary<k,v> and Hashtable are the same: add elements, delete elements, and access values by key in the same way.
  56. Different points of dictionary<k,v> and Hashtable:
  57. Dictionary<k,v> has a type constraint on the added element, Hashtable can add any type of element.
  58. The dictionary<k,v> does not require boxing, unpacking, Hashtable adding fashion boxes, and unpacking when reading.
  59. In the Dictionary<k,v> collection, in addition to the method of obtaining a value by key, there is also a trygetvalue (key) method that can get the value by key, the return value of the method is Boolean, if there is a value corresponding to the key, returns true, otherwise returns false. Avoids exceptions that occur because the corresponding values are not obtained.
  60. Using System;
  61. Using System.Collections.Generic;
  62. Class Program
  63. {
  64. static void Main ()
  65. {
  66. Create DICTIONARY<K,V>, and then add elements
  67. Dictionary < string, string > film = new Dictionary < string, string > ();
  68. Film. Add ("Wei Xiaobao", "Deer Ding kee");
  69. Film. Add ("clan", "Clan Legends");
  70. Film. Add ("Zhang Mowgli", "Yi Tian Tu Long kee");
  71. Film. Add ("Yang-Over", "the Condor- Man");
  72. Film. ADD ("Make Fox punch", "laugh proud of the Lake");
  73. Console.WriteLine ("The collection now has a number of {0} elements", film. Count);
  74. Film. Remove ("Yang Over");
  75. Iterating through the collection
  76. Console.WriteLine ("The protagonist and movie name of the martial arts film");
  77. Console.WriteLine ("/t lead/t movie");
  78. foreach (KeyValuePair < string, string > kvp in film)
  79. {
  80. Console.WriteLine ("/t{0}/t{1}", kvp. Key, kvp. Value);
  81. }
  82. Checks if an element exists, if it does not exist, adds
  83. if (!film. ContainsKey ("Duan Yu"))
  84. {
  85. Film. ADD ("Duan Yu", "Tianlong Eight");
  86. }
  87. Gets the collection of keys
  88. Dictionary < string, string >. KeyCollection keys = film. Keys;
  89. A collection of traversal keys
  90. Console.WriteLine ("The protagonist's name in the popular martial arts film");
  91. foreach (string str in keys)
  92. {
  93. Console.WriteLine (str);
  94. }
  95. Dictionary < string, string >. ValueCollection values = film. Values;
  96. Iterating over a collection of values
  97. Console.WriteLine ("The most popular martial arts film");
  98. foreach (string strfilm in values)
  99. {
  100. Console.WriteLine (Strfilm);
  101. }
  102. Another way to traverse an element
  103. Console.WriteLine ("The same traversal element method as the hash table");
  104. foreach (string strname in film. Values)
  105. {
  106. Console.WriteLine (strname);
  107. }
  108. Gets the value corresponding to the key
  109. String myfilm = film["make Fox Punch"];
  110. Console.WriteLine ("protagonist for the movie name of the Fox Chong {0}", myfilm);
  111. TryGetValue method to get the corresponding value of the key
  112. String objfilm = string. Empty;
  113. if (film. TryGetValue ("Duan Yu", Out objfilm))
  114. {
  115. Console.WriteLine ("The protagonist for the film of the Duan Yu is {0}", objfilm);
  116. }
  117. Else
  118. Console.WriteLine ("No protagonist for the film of the paragraph Reputation");
  119. Console.readkey ();
  120. }
  121. }
  122. The code creates a Dictionary<k,v> collection, the data type of the key and the value is a string type, the element behind the code is added, the deletion is the same as the hash table processing method, and the data type cast is not required to traverse the element. Dictionary<k,v> by the TryGetValue method of the key value, this method includes two parameters, one to query the key, and the other to get the value, note the value before using the Out keyword.
  123. Note: When using the TryGetValue method, the parameter must use the Out keyword, otherwise the compilation fails.
  124. Original link: http://www.code-design.cn/article/20120210/csharp-generic-collection-dictionary.aspx

C # Generic collection of dictionary<k, v> usage tips

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.