在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# Dictionary 循环

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

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