C# 遍历字典 (Dictionary) 的方法
可以使用 foreach 循环来遍历字典 (Dictionary)。每个键值对 (KeyValuePair) 都可以通过 foreach 循环中的变量进行访问。
例如:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// 添加元素到字典中
myDictionary.Add('apple', 1);
myDictionary.Add('banana', 2);
myDictionary.Add('orange', 3);
// 遍历字典
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine('Key = {0}, Value = {1}', kvp.Key, kvp.Value);
}
输出结果为:
Key = apple, Value = 1
Key = banana, Value = 2
Key = orange, Value = 3
其中,kvp.Key 表示字典中的键,kvp.Value 表示字典中的值。
原文地址: https://www.cveoy.top/t/topic/oDs3 著作权归作者所有。请勿转载和采集!