C#中的Dictionary

Dictionary<TKey, TValue> 是一个泛型集合,它存储键值对(key-value pairs),其中每个键(key)都是唯一的。这个集合类提供了快速的数据插入和检索功能,因为它是基于哈希表实现的。

注意 key不能重复,如果key重复了,系统就会报错

  1. 泛型Dictionary 是泛型集合,这意味着你可以指定存储在字典中的键和值的数据类型。例如,Dictionary<string, int> 表示键是字符串类型,值是整数类型。

  2. 添加元素:使用 Add 方法或索引器来添加键值对。如果键已经存在,Add 方法会更新对应的值。

    Dictionary<string, int> scores = new Dictionary<string, int>();
    scores.Add("Alice", 90);
    scores["Bob"] = 85; // 使用索引器添加或更新
  3. 检索元素:使用索引器通过键来检索值。

    复制
    int aliceScore = scores["Alice"];
  4. 检查键是否存在:使用 ContainsKey 方法来检查字典中是否存在特定的键。

    if (scores.ContainsKey("Alice"))
    {
        Console.WriteLine("Alice is in the dictionary.");
    }
  5. 遍历字典:可以使用 foreach 循环遍历字典中的所有键值对。

    foreach (KeyValuePair<string, int> kvp in scores)
    {
        Console.WriteLine($"Name: {kvp.Key}, Score: {kvp.Value}");
    }
  6. 移除元素:使用 Remove 方法来移除键值对。如果键不存在,Remove 方法会返回 false

    scores.Remove("Alice");
  7. 获取键和值的集合:可以使用 KeysValues 属性来获取字典中所有键和值的集合。

    IEnumerable<string> keys = scores.Keys;
    IEnumerable<int> values = scores.Values;
  8. 获取元素数量:使用 Count 属性来获取字典中元素的数量。

    int count = scores.Count;
  9. 清空字典:使用 Clear 方法来移除字典中的所有元素。

    scores.Clear();
  10. TryGetValue 方法:尝试获取与指定键相关联的值,如果键存在,返回 true 并输出值;如果不存在,返回 false

    int value;
    if (scores.TryGetValue("Alice", out value))
    {
        Console.WriteLine($"Alice's score is {value}.");
    }
    else
    {
        Console.WriteLine("Alice is not in the dictionary.");
    }

注意 Dictionary的使用索引器查找元素的时候 和数组不一样 不是从0开始 而是根据你添加的tkey寻找

相关推荐

  1. C#Dictionary

    2024-07-11 12:10:07       19 阅读
  2. C# Dictionary<TKey, TValue> 类

    2024-07-11 12:10:07       26 阅读
  3. C#面:介绍 Hashtable 和 Dictionary区别

    2024-07-11 12:10:07       32 阅读
  4. C# Dictionary<string, string> 对key做筛选

    2024-07-11 12:10:07       40 阅读
  5. C#(Unity)循环遍历Dictionary,并修改内容或删除内容

    2024-07-11 12:10:07       37 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 12:10:07       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 12:10:07       56 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 12:10:07       46 阅读
  4. Python语言-面向对象

    2024-07-11 12:10:07       57 阅读

热门阅读

  1. C语言标准库中的函数

    2024-07-11 12:10:07       22 阅读
  2. MVC分页

    MVC分页

    2024-07-11 12:10:07      24 阅读
  3. 整数 d → 字符 ‘d‘ 的转换代码为:d+‘0‘

    2024-07-11 12:10:07       20 阅读
  4. 进阶版智能家居系统Demo[C#]:整合AI和自动化

    2024-07-11 12:10:07       21 阅读
  5. 【C语言】C语言可以做什么?

    2024-07-11 12:10:07       20 阅读
  6. Windows图形界面(GUI)-SDK-C/C++ - 按钮(button)

    2024-07-11 12:10:07       23 阅读
  7. [C++]继承

    2024-07-11 12:10:07       20 阅读
  8. 小笔记(1)

    2024-07-11 12:10:07       18 阅读