1. To use the dictionary collection, you need to import the C # generic namespace
System.Collections.Generic//assembly: mscorlib
Description of 2.Dictionary
A mapping from a set of keys (key) to a set of values (value), each of which is composed of a value and its associated key
Any key must be unique
The key cannot be a null reference null (Nothing in VB), and if the value is a reference type, a null value can be
Key and value can be of any type (String,int,custom class, etc.)
3.Dictionary common usage: type of key is int, type of value is string for example
Create and initialize
Dictionary<int,string> mydictionary=new dictionary<int,string> ();
adding elements
Mydictionary.add (1, "C #"), Mydictionary.add (2, "C + +"), Mydictionary.add (3, "ASP"), Mydictionary.add (4, "MVC");
Find elements by key
if (Mydictionary.containskey (1)) {Console.WriteLine ("Key:{0},value:{1}", "1", mydictionary[1]);}
Traversing elements through KeyValuePair
foreach (keyvaluepair<int,string> kvp in mydictionary) { Console.WriteLine ("Key = {0}, Value = {1}", kvp. Key, kvp. Value);}
Traverse key Keys Property only
Dictionary<int,string>. KeyCollection KeyCol = Mydictionary.keys;foreach (Intkeyinkeycol) {Console.WriteLine ("key = {0}", key);}
Traverse only the Value Valus property
Dictionary<int,string>. ValueCollection Valuecol = Mydictionary.values;foreach (Stringvalueinvaluecol) {Console.WriteLine ("value = {0}", value );}
Remove the specified key value from the Remove method
Mydictionary.remove (1), if (Mydictionary.containskey (1)) {Console.WriteLine ("Key:{0},value:{1}", "1", myDictionary[ 1]);} else{ Console.WriteLine ("Does not exist key:1"); }
4. description of other common properties and methods:
comparer://Gets the IEqualityComparer used to determine whether the keys in the dictionary are equal. Count://Gets the number of key/value pairs contained in the dictionary. Item://Gets or sets the value associated with the specified key. Keys://Gets the collection that contains the keys in the dictionary. Values://Gets the collection that contains the values in the dictionary. Add://Adds the specified key and value to the dictionary. Clear://Remove all keys and values from the dictionary. ContainsKey://Determines whether the dictionary contains the specified key. Containsvalue://Determines whether the dictionary contains a specific value. GetEnumerator://Returns an enumerator that iterates through the dictionary. GetType://Gets the Type of the current instance. (Inherit from Object.) Remove://Removes the value of the specified key from the dictionary. ToString://Returns a String that represents the current object. (Inherit from Object.) ) TryGetValue://Gets the value associated with the specified key.