温馨提示×

c#怎么遍历字典中的键和值

c#
小亿
258
2024-03-20 09:52:51
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> dic = new Dictionary<string, int>();
        dic.Add("apple", 10);
        dic.Add("banana", 20);
        dic.Add("cherry", 30);

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

在上面的示例中,我们首先创建了一个包含键值对的字典dic,然后使用foreach循环遍历字典中的每个键值对,通过KeyValuePair<string, int>来获取键和值,最后打印出键和值。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在C#字典遍历中修改值

0