c# 实现遍历 Dictionary的方法?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
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]}");
}
仔细看这个 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--;
}
}
}
}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。