c#中keyvaluepair的用法是什么

c#
小億
222
2024-03-12 09:46:25
欄目: 編程語言

在C#中,KeyValuePair是一種泛型結(jié)構(gòu),用于存儲(chǔ)鍵值對(duì)數(shù)據(jù)。它可以將一個(gè)鍵和一個(gè)值關(guān)聯(lián)在一起,并且允許同時(shí)訪問鍵和值。KeyValuePair通常用于在字典或集合中存儲(chǔ)數(shù)據(jù)。

下面是一個(gè)示例,演示了如何使用KeyValuePair:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創(chuàng)建一個(gè)KeyValuePair
        KeyValuePair<int, string> pair = new KeyValuePair<int, string>(1, "apple");

        // 訪問鍵和值
        Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");

        // 在字典中使用KeyValuePair
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(pair.Key, pair.Value);

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

在上面的示例中,我們首先創(chuàng)建了一個(gè)KeyValuePair對(duì)象,然后訪問了其鍵和值。接著,我們將KeyValuePair對(duì)象添加到一個(gè)字典中,并通過foreach循環(huán)遍歷字典中的所有KeyValuePair。KeyValuePair提供了一種方便的方式來處理鍵值對(duì)數(shù)據(jù)。

0