昨天在 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)