您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    遍历 Dictionary,你会几种方式?
    时间:2020-09-28 21:21 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

    遍历 Dictionary,你会几种方式?

    昨天在 StackOverflow 上看到一个很幽默的成绩,说: 你会几种遍历字典的方式,然后跟帖就是各种奇葩的回答,挺有意思,马上就要国庆了,文娱文娱吧,说说这种挺无聊的成绩。

    二: 运用 foreach 遍历

    为了方便演示,先上一段测试代码:

    var dict = new Dictionary<int, string>() 

                {                [10] = "A10"

                    [20] = "A20"

                    [30] = "A30"

                    [40] = "A40"

                    [50] = "A50" 

                }; 

    1. 直接 foreach dict

    假设要拿百分比说话,估量有 50%+ 的小同伴用这种方式,为啥,复杂粗犷呗,其他没什么好说的,直接上代码:

    foreach (var item in dict) 

               {                Console.WriteLine($"key={item.Key},value={item.Value}"); 

               } 

    这里的 item 是底层在 MoveNext 的进程中用 KeyValuePair 包装出来的,假设你不信的话,看下源码呗:

    public bool MoveNext() 

       {        while ((uint)_index < (uint)_dictionary._count) 

           {            ref Entry reference = ref _dictionary._entries[_index++]; 

               if (reference.next >= -1) 

               {                _current = new KeyValuePair<TKey, TValue>(reference.key, reference.value); 

                   return true

               }        }    } 

    2. foreach 中 运用 KeyPairValue 解构

    刚才你也看到了 item 是 KeyValuePair 类型,不过的是 netcore 对 KeyValuePair 停止了增强,添加了 Deconstruct 函数用来解构 KeyValuePair,代码如下:

    public readonly struct KeyValuePair<TKey, TValue> 

        {        private readonly TKey key

            private readonly TValue value; 

            public TKey Key => key

            public TValue Value => value; 

            public KeyValuePair(TKey key, TValue value) 

            {            this.key = key

                this.value = value; 

    (责任编辑:admin)