SoFunction
Updated on 2025-03-07

7 common usages of Dictionary generic collections in C#

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

 

Copy the codeThe code is as follows:
Dictionary<int,string>myDictionary=newDictionary<int,string>();

2. Add elements

Copy the codeThe code is as follows:
(1,"C#");
(2,"C++");
(3,"");
(4,"MVC");

3. Find elements through Key

Copy the codeThe code is as follows:
if((1))
{
("Key:{0},Value:{1}","1", myDictionary[1]);
}

4. Traverse elements through KeyValuePair

Copy the codeThe code is as follows:
foreach(KeyValuePair<int,string>kvp in myDictionary)
{
("Key = {0}, Value = {1}",, );
}

5. Only traverse the keys attributes

Copy the codeThe code is as follows:
Dictionary<int,string>.KeyCollection keyCol=;
foreach(intkeyinkeyCol)
{
("Key = {0}", key);
}

6. Only traverse the value Valus attribute

Copy the codeThe code is as follows:
Dictionary<int,string>.ValueCollection valueCol=;
foreach(stringvalueinvalueCol)
{
("Value = {0}", value);
}

7. Remove the specified key value through the Remove method

Copy the codeThe code is as follows:
(1);
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.