C# 遍历 Dictionary 数组:使用 for 循环和 GetEnumerator() 方法
要循环遍历一个 Dictionary 数组,可以使用 for 循环来迭代每个 Dictionary 元素。 然后,可以使用 Dictionary 的 GetEnumerator() 方法获取一个 DictionaryEnumerator 对象,通过调用其 MoveNext() 和 Current 属性来访问每个键值对。
以下是一个示例代码:
Dictionary<string, int>[] dictionaries = new Dictionary<string, int>[]
{
new Dictionary<string, int> { { 'Apple', 1 }, { 'Banana', 2 }, { 'Orange', 3 } },
new Dictionary<string, int> { { 'Cat', 4 }, { 'Dog', 5 }, { 'Bird', 6 } },
};
foreach (var dictionary in dictionaries)
{
var enumerator = dictionary.GetEnumerator();
while (enumerator.MoveNext())
{
var kvp = enumerator.Current;
Console.WriteLine($'Key: {kvp.Key}, Value: {kvp.Value}');
}
}
这段代码会输出以下内容:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Orange, Value: 3
Key: Cat, Value: 4
Key: Dog, Value: 5
Key: Bird, Value: 6
原文地址: https://www.cveoy.top/t/topic/p6JN 著作权归作者所有。请勿转载和采集!