在 C# 中,可以使用 foreach 循环来遍历字典 (Dictionary) 中的键值对。以下是一个示例:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("A", 1);
dictionary.Add("B", 2);
dictionary.Add("C", 3);

foreach (KeyValuePair<string, int> kvp in dictionary)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}

输出结果为:

Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3

在循环中,我们使用了 KeyValuePair<string, int> 来声明循环变量 kvp,其中 string 为键的类型,int 为值的类型。然后,我们可以通过 kvp.Key 获取键,通过 kvp.Value 获取值。在循环体中,可以根据需要进行任何操作。

另外,也可以只循环字典的键或值,而不是键值对。以下是分别循环字典的键和值的示例:

foreach (string key in dictionary.Keys)
{
    Console.WriteLine("Key: " + key);
}

foreach (int value in dictionary.Values)
{
    Console.WriteLine("Value: " + value);
}

这样,输出结果分别为:

Key: A
Key: B
Key: C

Value: 1
Value: 2
Value: 3
C# 字典循环:遍历键值对、键和值 - 示例代码

原文地址: https://www.cveoy.top/t/topic/p6JY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录