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.