【转载】C# Dictionary(数据字典)的基本用法

191 阅读3分钟

原文链接

C# Dictionary(数据字典)的基本用法 | 猫先生~

正文

通常情况下,我们可以通过 int 类型的索引来从数组或者 List 集合中查询所需的数据

但是如果情况稍微复杂一点:索引是非 int 类型的数据(比如 string 或其他类型),这时候就需要使用字典

顾名思义,数据字典就是一种让我们可以通过索引查询到特定数据的数据结构类型,它的关键字就是:Dictionary

Dictionary 用法

1、value字符串 类型的值:Dictionary<string,string> MyDt = new Dictionary<string,string>()

2、value对象 类型的值:Dictionary<string,List<object>> myDt = new Dictionary<string,List<object>>()

序号方法/属性说明
1MyDt.Add("1","a")添加一个元素
2MyDt.Remove("1","a")删除一个元素
3MyDt["1"] ="b"修改一个元素值
4string value = MyDt["1"]获取一个元素值/通过 key 查找元素
5MyDt.ContainsKey("2")判断键是否存在
6MyDt.ContainsValue("a")判断值是否存在
7MyDt.Clear()清空字典
8MyDt.Count()返回字典元素个数

Dictionary 注意事项

  1. C# 的 Dictionary<Tkey,TValue> 通过类在内部维护两个数组来实现功能:一个 keys 数组容纳要从其映射的键,另一个 values 容纳映射到的值

    • Dictionary<Tkey,TValue> 集合中插入键 / 值对时,将自动记录哪个键和哪个值关联,从而允许开发人员快速和简单地获取具有指定键的值
  2. C# Dictionary<Tkey,TValue> 集合不能包含 重复 的键:调用 Add 方法添加键数组中已有的键将抛出 异常

    • 可用 ContainKey 方法测试 Dictionary<Tkey,TValue> 集合是否已包含特定的键
  3. Dictionary<Tkey,TValue> 集合内部采用一种 稀疏 数据结构,在有大量内存可用时才最 高效

    • 随着更多元素的插入,Dictionary<Tkey,TValue> 集合可能快速消耗大量的内存
  4. foreach 遍历 Dictionary<Tkey,TValue> 集合返回一个 KeyValuePair<Tkey,TValue>

    • 该结构包含数据项的键和值拷贝,可通过 KeyValue 属性访问每个元素
    • 获得的元素是只读的,不能用它们修改 Dictionary<Tkey,TValue> 集合中的数据

Dictionary 遍历

遍历方法:

  • 遍历 Key
  • 遍历 Value
  • 遍历 Key-Value
  • 遍历 stringValue
static void Main(string[] args)
{
      //创建一个字典
      Dictionary<int, string> MyDh = new Dictionary<int, string>();
      MyDh.Add(1, "aaa");
      MyDh.Add(2, "bbb");
      MyDh.Add(3, "ccc");
      MyDh.Add(4, "ddd");
    
      //遍历 Key
      Console.WriteLine("遍历 Key 结果:");
      foreach (int Key in MyDh.Keys)
      {
           Console.WriteLine(Key);
       }
    
       //遍历 Value
       Console.WriteLine("遍历 Value 结果:");
       foreach (string value in MyDh.Values)
       {
           Console.WriteLine(value);
        }
    
        //遍历 Key-Value
        Console.WriteLine("遍历 Key-Value 结果:");
        foreach (KeyValuePair<int, string> item in MyDh)
        {
           Console.WriteLine(item.Key + "\t" + item.Value);
        }
 }

遍历得到的结果如下:

image.png

Dictionary 取值

常用的取值方法有 2 种:

方法 1:先判断是否存在,如果存在再进行取值

if(aDictionary.ContainsKey(key))
{
    var value = Dictionary[key];
}

方法 2:使用 TryGetValue

int value;
aDictionary.TryGetValue(key, out value);

在项目中,如果只是取值,推荐 使用 TryGetValue 来获取

原因

方法 1ContainsKey 执行了一次方法,Dictionary[Key] 再次执行了一次方法,整个取值过程调用了两次方法

方法 2TryGetValue 只调用了一次方法,当然并不是调用的方法越多就越耗性能

判断在字典中是否存在一般会通过 Key 来获取 HashCode,然后通过 Equal 对值进行比对

字典存储中会给 Key 一个对应的 HashCode,如果数据过多,那么 HashCode 也可能 重复,所以需要再次进行比较,时间主要花费在这上面

总结

如果只是取值,直接用 TryGetValue 花费更小、更快、更安全,找不到 Value 时将返回 False