遍历Dictionary,你会几种方式?

一:背景

创新互联秉承实现全网价值营销的理念,以专业定制企业官网,成都网站建设、做网站,成都微信小程序,网页设计制作,移动网站建设全网营销推广帮助传统企业实现“互联网+”转型升级专业定制企业官网,公司注重人才、技术和管理,汇聚了一批优秀的互联网技术人才,对客户都以感恩的心态奉献自己的专业和所长。

1. 讲故事

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

二: 使用 foreach 遍历

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

 
 
 
 
  1. var dict = new Dictionary()
  2.             {                [10] = "A10",
  3.                 [20] = "A20",
  4.                 [30] = "A30",
  5.                 [40] = "A40",
  6.                 [50] = "A50"
  7.             };

1. 直接 foreach dict

如果要拿百分比说话,估计有 50%+ 的小伙伴用这种方式,为啥,简单粗暴呗,其他没什么好说的,直接上代码:

 
 
 
 
  1. foreach (var item in dict)
  2.            {                Console.WriteLine($"key={item.Key},value={item.Value}");
  3.            }

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

 
 
 
 
  1. public bool MoveNext()
  2.    {        while ((uint)_index < (uint)_dictionary._count)
  3.        {            ref Entry reference = ref _dictionary._entries[_index++];
  4.            if (reference.next >= -1)
  5.            {                _current = new KeyValuePair(reference.key, reference.value);
  6.                return true;
  7.            }        }    }

2. foreach 中 使用 KeyPairValue 解构

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

 
 
 
 
  1. public readonly struct KeyValuePair
  2.     {        private readonly TKey key;
  3.         private readonly TValue value;
  4.         public TKey Key => key;
  5.         public TValue Value => value;
  6.         public KeyValuePair(TKey key, TValue value)
  7.         {            this.key = key;
  8.             this.value = value;
  9.         }        public void Deconstruct(out TKey key, out TValue value)
  10.         {            key = Key;            value = Value;
  11.         }    }

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

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

3. foreach keys

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

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

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

 
 
 
 
  1. public struct Enumerator : IEnumerator>, IDisposable, IEnumerator, IDictionaryEnumerator
  2. {    public bool MoveNext()
  3.     {        while ((uint)_index < (uint)_dictionary._count)
  4.         {            ref Entry reference = ref _dictionary._entries[_index++];
  5.             if (reference.next >= -1)
  6.             {                _current = new KeyValuePair(reference.key, reference.value);
  7.                 return true;
  8.             }        }        _index = _dictionary._count + 1;
  9.         _current = default(KeyValuePair);
  10.         return false;
  11.     }}

仔细看这个 while 循环,你就应该明白,本质上它也是对 entries 数组进行遍历,那底层都用了 while,我是不是可以用 for 来替换然后循环 dict 呢?哈哈,反正就是模仿呗。

三:使用 for 遍历

为了把 MoveNext 中的代码模拟出来,重点在于这条语句: ref Entry reference = ref _dictionary._entries[_index++];, 其实很简单,_entries 数组内容的提取可以用 Linq 的 ElementAt 方法,是不是~ ,改造后的代码如下:

 
 
 
 
  1. for (int i = 0; i < dict.Count; i++)
  2. {                (int key, string value) = dict.ElementAt(i);
  3.     Console.WriteLine($"key={key},value={dict[key]}");
  4. }

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

 
 
 
 
  1. public static TSource ElementAt(this IEnumerable source, int index)
  2. {        IList list = source as IList;
  3.     if (list != null)
  4.     {            return list[index];
  5.     }        if (index >= 0)
  6.     {            using (IEnumerator enumerator = source.GetEnumerator())
  7.         {                while (enumerator.MoveNext())
  8.             {                    if (index == 0)
  9.                 {                        return enumerator.Current;
  10.                 }                    index--;                }            }        }    }

从上面代码可以看到,如果当前的 source 没有实现 IList 接口的话,那就是一个巨大的坑,每一次执行 ElementAt 方法,最坏时间复杂度都是 O(N),就拿刚才的 for循环来说,它的最坏时间复杂度就是 O(n!) ,是不是比你想象的要恐怖的多,教训就是多实践,多看看源码~

四:总结

这篇列举了 4 种遍历 dict 的方式,不知你会用到哪几种? 要注意的是最后 ElementAt 对 Source 判别上的大坑一定要明白,不要想当然的以为就是 O(N) ,好了,更多的 遍历方式 欢迎补充!

新闻标题:遍历Dictionary,你会几种方式?
转载源于:http://www.hantingmc.com/qtweb/news17/44467.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联