RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Dictionary遍历的使用方法有哪些

本篇内容主要讲解“Dictionary遍历的使用方法有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Dictionary遍历的使用方法有哪些”吧!

创新互联凭借专业的设计团队扎实的技术支持、优质高效的服务意识和丰厚的资源优势,提供专业的网站策划、成都网站建设、成都网站设计、网站优化、软件开发、网站改版等服务,在成都10余年的网站建设设计经验,为成都上千多家中小型企业策划设计了网站。

 使用 foreach 遍历

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

var dict = new Dictionary()             {                [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}");            }
Dictionary遍历的使用方法有哪些

这里的 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(reference.key, reference.value);                return true;            }        }    }

2. foreach 中 使用 KeyPairValue 解构

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

public readonly struct KeyValuePair     {        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}");             }
Dictionary遍历的使用方法有哪些

3. foreach keys

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

foreach (var key in dict.Keys)           {                Console.WriteLine($"key={key},value={dict[key]}");           }
Dictionary遍历的使用方法有哪些

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

public struct Enumerator : IEnumerator>, 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(reference.key, reference.value);                 return true;             }        }        _index = _dictionary._count + 1;         _current = default(KeyValuePair);         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]}"); }
Dictionary遍历的使用方法有哪些

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

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

到此,相信大家对“Dictionary遍历的使用方法有哪些”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


名称栏目:Dictionary遍历的使用方法有哪些
网站地址:http://sczitong.cn/article/jcjdch.html