To use Dictionary collection, you need to import the C# generic namespace
(Assembly: mscorlib)
Description of Dictionary
1. Mapping from a set of keys to a set of values (Values), each added item is composed of a value and its associated keys.
2. Any key must be unique
3. The key cannot be null referenced null (Nothing in VB). If the value is a reference type, it can be null.
4. Key and Value can be of any type (string, int, custom class, etc.)
Common usage of Dictionary: Take the type of key as int and the type of value as string as an example
1. Creation and initialization
2. Add elements
(2,"C++");
(3,"");
(4,"MVC");
3. Find elements through Key
{
("Key:{0},Value:{1}","1", myDictionary[1]);
}
4. Traverse elements through KeyValuePair
{
("Key = {0}, Value = {1}",, );
}
5. Only traverse the keys attributes
foreach(intkeyinkeyCol)
{
("Key = {0}", key);
}
6. Only traverse the value Valus attribute
foreach(stringvalueinvalueCol)
{
("Value = {0}", value);
}
7. Remove the specified key value through the Remove method
if((1))
{
("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
("No Key : 1");
}
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 Dictionary. |
Item: | Gets or sets the value associated with the specified key. |
Keys: | Gets a collection containing keys in Dictionary. |
Values: | Gets a collection containing values in Dictionary. |
Add: | Adds the specified key and value to the dictionary. |
Clear: | Remove all keys and values from Dictionary. |
ContainsKey: | Determines whether Dictionary contains the specified key. |
ContainsValue: | Determines whether Dictionary contains a specific value. |
GetEnumerator: | Returns the enumeration number that loops through the Dictionary. |
GetType: | Gets the Type of the current instance. (Inherited from Object.) |
Remove: | Removes the value of the specified key from the Dictionary. |
ToString: | Returns the String representing the current Object. (Inherited from Object.) |
TryGetValue: | Gets the value associated with the specified key. |