c#

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

小亿
126
2024-03-20 09:52:51
栏目: 编程语言

在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>来获取键和值,最后打印出键和值。

0
看了该问题的人还看了