关于c#:遍历-Dictionary你会几种方式

9次阅读

共计 2860 个字符,预计需要花费 8 分钟才能阅读完成。

一:背景

1. 讲故事

昨天在 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;
        }

        public void Deconstruct(out TKey key, out TValue value)
        {
            key = Key;
            value = Value;
        }
    }

有了这个解构函数,你就能够在遍历的过程中间接拿到 key,value,而不是包装的 KeyValuePair,这在 netframework 中可是不行的哈,实现代码如下:


            foreach ((int key, string value) in dict)
            {Console.WriteLine($"key={key},value={value}");
            }

3. foreach keys

后面的例子都是间接对 dict 进行 foreach,其实你还能够对 dict.keys 进行 foreach 遍历,而后通过遍历出的 key 对 dict 进行类索引器读取,代码如下:


            foreach (var key in dict.Keys)
            {Console.WriteLine($"key={key},value={dict[key]}");
            }

说到这里,不晓得你是否有一个潜意识,那就是 dict 只能通过 foreach 进行遍历,假相是不是这样的呢?要寻找答案,还是回头看一下 foreach 是如何进行遍历的。


public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IEnumerator, IDictionaryEnumerator
{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;
            }
        }
        _index = _dictionary._count + 1;
        _current = default(KeyValuePair<TKey, TValue>);
        return false;
    }
}

认真看这个 while 循环,你就应该明确,实质上它也是对 entries 数组进行遍历,那底层都用了 while,我是不是能够用 for 来替换而后循环 dict 呢?哈哈,反正就是模拟呗。

三:应用 for 遍历

为了把 MoveNext 中的代码模仿进去,重点在于这条语句:ref Entry reference = ref _dictionary._entries[_index++];, 其实很简略,_entries 数组内容的提取能够用 Linq 的 ElementAt 办法,是不是~~~,革新后的代码如下:


            for (int i = 0; i < dict.Count; i++)
            {(int key, string value) = dict.ElementAt(i);

                Console.WriteLine($"key={key},value={dict[key]}");
            }

接下来是不是很好奇这个 ElementAt 扩大办法是如何实现的,一起看看源码吧。


    public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index)
    {
        IList<TSource> list = source as IList<TSource>;
        if (list != null)
        {return list[index];
        }
        if (index >= 0)
        {using (IEnumerator<TSource> enumerator = source.GetEnumerator())
            {while (enumerator.MoveNext())
                {if (index == 0)
                    {return enumerator.Current;}
                    index--;
                }
            }
        }
    }

从下面代码能够看到,如果以后的 source 没有实现 IList 接口的话,那就是一个微小的坑,每一次执行 ElementAt 办法,最坏工夫复杂度都是 O(N),就拿方才的 for 循环来说,它的最坏工夫复杂度就是 O(n!),是不是比你设想的要恐怖的多,教训就是多实际,多看看源码~

四:总结

这篇列举了 4 种遍历 dict 的形式,不知你会用到哪几种?要留神的是最初 ElementAt 对 Source 判断上的大坑肯定要明确,不要想当然的认为就是 O(N),好了,更多的 遍历形式 欢送补充!

更多高质量干货:参见我的 GitHub: dotnetfly

正文完
 0