溫馨提示×

c# keyvaluepair怎樣實現

c#
小樊
129
2024-11-20 06:27:08
欄目: 編程語言

在C#中,你可以使用KeyValuePair<TKey, TValue>類來表示一個鍵值對。這個類位于System.Collections.Generic命名空間中。下面是一個簡單的示例,展示了如何使用KeyValuePair<TKey, TValue>

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個 KeyValuePair 列表
        List<KeyValuePair<string, int>> keyValuePairs = new List<KeyValuePair<string, int>>();

        // 添加一些鍵值對到列表中
        keyValuePairs.Add(new KeyValuePair<string, int>("apple", 1));
        keyValuePairs.Add(new KeyValuePair<string, int>("banana", 2));
        keyValuePairs.Add(new KeyValuePair<string, int>("orange", 3));

        // 遍歷列表并輸出鍵值對
        foreach (KeyValuePair<string, int> pair in keyValuePairs)
        {
            Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
        }
    }
}

在這個示例中,我們創建了一個List<KeyValuePair<string, int>>類型的變量keyValuePairs,用于存儲字符串鍵和整數值的鍵值對。然后,我們使用Add方法向列表中添加了一些鍵值對。最后,我們使用foreach循環遍歷列表并輸出每個鍵值對的鍵和值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女