[C# Basic Intensive Lecture] The use of Dictionary (Dictionary)

insert image description here

In C#, Dictionary<TKey, TValue>it is a very commonly used generic collection class for storing key-value pairs (Key-Value Pair) data structure. Dictionary<TKey, TValue>You can quickly find the corresponding value according to the key, so in the scenario where you need to quickly find and retrieve data, especially when a large amount of data is involved, using a dictionary is a very efficient choice. This article will introduce Dictionary<TKey, TValue>the applications in detail, including creating dictionaries, adding elements, accessing elements, deleting elements, traversing dictionaries, common methods, etc.

1. Create a dictionary

To use it Dictionary<TKey, TValue>, you also need to introduce System.Collections.Generica namespace. When creating a dictionary, you need to specify the types of keys and values, for example, if we want strings as keys and integers as values, create a type of Dictionary<string, int>dictionary.

using System.Collections.Generic;

// 创建一个以字符串作为键,以整数作为值的字典
Dictionary<string, int> ageDict = new Dictionary<string, int>();

In the above code, we created a Dictionary<string, int>type of dictionary ageDictto store the correspondence between people's names and ages.

2. Add elements

Add()You can add key-value pairs to the dictionary using the method. If the key already exists in the dictionary, Add()the method will throw an exception. If we want the keys to be repeatable, we can use the index notation to []directly assign values ​​to the dictionary, so that if the key already exists, the corresponding value will be updated.

// 添加键值对到字典中
ageDict.Add("Alice", 25);
ageDict.Add("Bob", 30);
ageDict.Add("Charlie", 22);

// 直接赋值给字典,如果键已存在,则更新对应的值
ageDict["Alice"] = 26;

In the above code, we ageDictadded three key-value pairs to the dictionary, and then ageDict["Alice"] = 26updated the value corresponding to the key "Alice" from 25 to 26.

3. Accessing elements

Values ​​in the dictionary can be accessed by key. Use the index notation []and key to get the corresponding value. An exception is thrown if the key does not exist in the dictionary. To avoid exceptions being thrown, TryGetValue()methods can be used.

// 通过键访问字典中的值
int aliceAge = ageDict["Alice"]; // 获取"Alice"对应的值,此处为26

// 使用 TryGetValue() 避免抛出异常
if (ageDict.TryGetValue("Bob", out int bobAge))
{
    
    
    Console.WriteLine($"Bob's age: {
      
      bobAge}"); // 输出"Bob's age: 30"
}
else
{
    
    
    Console.WriteLine("Bob's age not found.");
}

In the above code, we ageDict["Alice"]obtain the value corresponding to the key "Alice" and use TryGetValue()the method to obtain the value corresponding to the key "Bob". If the key "Bob" exists, assign the corresponding value to the variable bobAge, otherwise output "Bob's age not found.".

4. Delete elements

The method can be used Remove()to remove elements from a dictionary based on a key.

// 删除字典中的键值对
ageDict.Remove("Charlie");

In the above code, we use Remove()the method ageDictto delete the key-value pair corresponding to the key "Charlie" from the dictionary.

5. Iterating over the dictionary

You can use foreacha loop to iterate over all key-value pairs in a dictionary, or iterate over keys and values ​​separately.

// 遍历键值对
foreach (var kvp in ageDict)
{
    
    
    Console.WriteLine($"{
      
      kvp.Key}: {
      
      kvp.Value}");
}

// 遍历键
foreach (var key in ageDict.Keys)
{
    
    
    Console.WriteLine(key);
}

// 遍历值
foreach (var value in ageDict.Values)
{
    
    
    Console.WriteLine(value);
}

In the above code, we used foreacha loop to iterate over ageDictall key-value pairs, all keys, and all values ​​in the dictionary.

6. Dictionary<TKey, TValue>Common methods

In addition to the basic operations described above, Dictionary<TKey, TValue>many other commonly used methods are provided to facilitate operations on dictionaries. Some common methods are listed below:

Count

CountProperty is used to get the number of key-value pairs in the dictionary.

int count = ageDict.Count; // 获取键值对的数量,此处为2

In the above code, countit will be assigned a value of 2, indicating that ageDictthere are two key-value pairs in the dictionary.

ContainsKeyandContainsValue

ContainsKey()The method is used to determine whether the specified key is contained in the dictionary and returns a boolean value. ContainsValue()The method is used to determine whether the specified value is contained in the dictionary and returns a boolean value.

bool hasAlice = ageDict.ContainsKey("Alice"); // 判断字典是否包含键"Alice"
bool hasAge30 = ageDict.ContainsValue(30); // 判断字典是否包含值为30的元素

In the above code, hasAlicewill be assigned truebecause ageDictthe dictionary contains the key "Alice". Instead, hasAge30it will be assigned a value false, because ageDictthe value in the dictionary 26is and 22, there is no 30element with value.

Clear

Clear()method is used to empty the entire dictionary, that is, delete all key-value pairs.

ageDict.Clear(); // 清空字典

In the above code, all key-value pairs in the dictionary Clear()will be deleted, and the dictionary will become empty.ageDict

7. Application scenarios of dictionaries

Dictionaries are a very useful data structure, suitable for many scenarios. Here are some common application scenarios:

data index

Dictionaries are often used for data indexing to quickly find corresponding values ​​through unique keys. For example, you can use the dictionary to use the student's student number as the key and the student's name as the value to quickly find the student's name through the student number.

Dictionary<string, string> studentNameDict = new Dictionary<string, string>();
studentNameDict.Add("2021001", "Alice");
studentNameDict.Add("2021002", "Bob");
studentNameDict.Add("2021003", "Charlie");

string name = studentNameDict["2021002"]; // 获取学号为"2021002"的学生姓名,此处为"Bob"

Statistical frequency

Dictionaries can be used to count the frequency of occurrence of each element in a set of data. Keys can be data elements and values ​​can be frequencies.

List<string> fruitsList = new List<string> {
    
     "apple", "orange", "banana", "apple", "orange", "apple" };
Dictionary<string, int> fruitCountDict = new Dictionary<string, int>();

foreach (var fruit in fruitsList)
{
    
    
    if (fruitCountDict.ContainsKey(fruit))
    {
    
    
        fruitCountDict[fruit]++;
    }
    else
    {
    
    
        fruitCountDict.Add(fruit, 1);
    }
}

foreach (var kvp in fruitCountDict)
{
    
    
    Console.WriteLine($"{
      
      kvp.Key}: {
      
      kvp.Value}");
}

In the above code, we use the dictionary fruitCountDictto count fruitsListthe frequency of each fruit in the fruit list, and output the statistical results.

cache data

Dictionaries can be used to cache data to improve the efficiency of data access. In some scenarios, some data may need to be read frequently. In order to avoid repeated calculations or read data from the database, these data can be cached in the dictionary.

Dictionary<string, int> fibCache = new Dictionary<string, int>();

int Fibonacci(int n)
{
    
    
    if (n <= 1)
    {
    
    
        return n;
    }

    if (fibCache.ContainsKey(n.ToString()))
    {
    
    
        return fibCache[n.ToString()];
    }

    int result = Fibonacci(n - 1) + Fibonacci(n - 2);
    fibCache.Add(n.ToString(), result);
    return result;
}

In the above code, we implemented a function of the Fibonacci sequence Fibonacci(). In order to avoid repeated calculations, we cached the calculated results in fibCachethe dictionary.

8. Summary

Dictionary<TKey, TValue>It is a very commonly used generic collection class in C#, which is used to store the data structure of key-value pairs. This article introduces Dictionary<TKey, TValue>the applications, including creating dictionaries, adding elements, accessing elements, deleting elements, traversing dictionaries and commonly used methods. A dictionary is an efficient data structure, especially useful in scenarios where fast lookup and retrieval of data is required. I hope that through the introduction of this article, you can better understand and use it Dictionary<TKey, TValue>, so that you can process key-value pair data more flexibly and efficiently in C# programming. Best of luck with your C# programming!

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132227303