扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c#遍历字典的方法是什么

扬州沐宇科技
2024-03-12 10:19:21
c#

在C#中,可以使用foreach循环来遍历字典。以下是一个示例:

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);

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

上面的代码创建了一个包含字符串键和整数值的字典。然后使用foreach循环遍历字典中的每个键值对,并打印出键和对应的值。

扫码添加客服微信