溫馨提示×

c#怎么遍歷字典中的鍵和值

c#
小億
274
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女