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>>();

Dictionary 注意事项

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

  在 Dictionary<Tkey,TValue> 集合中插入键 / 值对时,将自动记录哪个键和哪个值关联,从而允许开发人员快速和简单地获取具有指定键的值

  • C# Dictionary<Tkey,TValue> 集合不能包含重复的键:调用 Add 方法添加键数组中已有的键将抛出异常

  可用 ContainKey 方法测试 Dictionary<Tkey,TValue> 集合是否已包含特定的键

  • Dictionary<Tkey,TValue> 集合内部采用一种稀疏数据结构,在有大量内存可用时才最高效

  随着更多元素的插入,Dictionary<Tkey,TValue> 集合可能快速消耗大量的内存

  • 用 foreach 遍历 Dictionary<Tkey,TValue> 集合返回一个 KeyValuePair<Tkey,TValue>

  该结构包含数据项的键和值拷贝,可通过 Key 和 Value 属性访问每个元素

  获得的元素是只读的,不能用它们修改 Dictionary<Tkey,TValue> 集合中的数据

Dictionary 遍历

遍历方法:

  1. 遍历 Key
  2. 遍历 Value
  3. 遍历 Key-Value
  • 遍历 string 型 value
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);
        }
 }

遍历得到的结果如下:

 

Dictionary 取值

常用的取值方法有 2 种:

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

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

方法 2:使用 TryGetValue

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

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

原因:

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

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

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

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

总结:

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

 

 

 

 

 

👉 |  以上内容仅为学习参考、学习笔记使用  | 👈

posted @ 2022-10-01 00:44  Mr.Cat~  阅读(9131)  评论(0编辑  收藏  举报