Seven Common Uses of Dictionary Generic Set in C

  • 2021-09-20 21:19:22
  • OfStack

To use the Dictionary collection, you need to import the C # generic namespace

System. Collections. Generic (Assembly: mscorlib)

Description of Dictionary
1. Mapping from 1 set of keys (Key) to 1 set of values (Value), where each addition consists of a value and its associated key

2. Any key must be 1-only

3. The key cannot be a null reference null (Nothing in VB). If the value is a reference type, it can be a null value

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. 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. Find elements through 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 traverse the key Keys property

Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
{
   Console.WriteLine("Key = {0}", key);
}

6. Only the value Valus property is traversed

Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
{
   Console.WriteLine("Value = {0}", value);
}

7. Remove the specified key value by Remove method

myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
   Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
   Console.WriteLine(" Nonexistent Key : 1");
}

Description of other common properties and methods:

Comparer: 获取用于确定字典中的键是否相等的 IEqualityComparer。
Count: 获取包含在 Dictionary中的键/值对的数目。
Item: 获取或设置与指定的键相关联的值。
Keys: 获取包含 Dictionary中的键的集合。
Values: 获取包含 Dictionary中的值的集合。
Add: 将指定的键和值添加到字典中。
Clear: 从 Dictionary中移除所有的键和值。
ContainsKey: 确定 Dictionary是否包含指定的键。
ContainsValue: 确定 Dictionary是否包含特定值。
GetEnumerator: 返回循环访问 Dictionary的枚举数。
GetType: 获取当前实例的 Type。 (从 Object 继承。)
Remove: 从 Dictionary中移除所指定的键的值。
ToString: 返回表示当前 Object的 String。 (从 Object 继承。)
TryGetValue: 获取与指定的键相关联的值。

Related articles: