DictionaryCommon usage: the key type is int, and the value type is string. 1. Create and initialize
Dictionary <int, string> myDictionary = newDictionary <int, string> ();
2. Add Elements
MyDictionary. Add (1, "C #");
MyDictionary. Add (2, "C ++ ");
MyDictionary. Add (3, "ASP. NET ");
MyDictionary. Add (4, "MVC ");
3. Search for elements by Key
If (myDictionary. ContainsKey (1 ))
{
Console. WriteLine ("Key: {0}, Value: {1}", "1", myDictionary [1]);
}
4. Traverse elements through KeyValuePair
Foreach (KeyValuePair <int, string> kvp in myDictionary)
...{
Console. WriteLine ("Key = {0}, Value = {1}", kvp. Key, kvp. Value );
}
5,Only the Keys attribute of the traversal key
Dictionary <int, string>. KeyCollection keyCol = myDictionary. Keys;
Foreach (intkeyinkeyCol)
...{
Console. WriteLine ("Key = {0}", key );
}
6. Only the Valus attribute is traversed.
Dictionary <int, string>. ValueCollection valueCol = myDictionary. Values;
Foreach (stringvalueinvalueCol)
...{
Console. WriteLine ("Value = {0}", value );
}
7. Remove the specified key value using the Remove Method.
MyDictionary. Remove (1 );
If (myDictionary. ContainsKey (1 ))
...{
Console. WriteLine ("Key: {0}, Value: {1}", "1", myDictionary [1]);
}
Else
{
Console. WriteLine ("Key not found: 1 ");
}
Other common attributes and methods:Comparer: Obtain the IEqualityComparer used to determine whether keys in the dictionary are equal.
Count: gets the number of key/value pairs contained in a Dictionary.
Item: gets or sets the value associated with the specified key.
Keys: gets a set of Keys that contain a Dictionary.
Values: gets a set that contains Values in a Dictionary.
Add: Add the specified key and value to the dictionary.
Clear: removes all keys and values from Dictionary.
ContainsKey: determines whether a Dictionary contains the specified key.
ContainsValue: determines whether a Dictionary contains a specific value.
GetEnumerator: returns the number of enumerations of the cyclically accessed Dictionary.
GetType: Get the Type of the current instance. (Inherit from Object .)
Remove: Remove the specified key value from Dictionary.
ToString: returns the String of the current Object. (Inherit from Object .)
TryGetValue: gets the value associated with the specified key.