在C#中,KeyValuePair是一個用于存儲鍵值對的無序集合。它位于System.Collections.Generic命名空間中。要使用KeyValuePair,首先需要創建一個KeyValuePair對象,然后將其添加到集合中,例如List或Dictionary。
以下是如何在C#中使用KeyValuePair的示例:
using System;
using System.Collections.Generic;
List<KeyValuePair<string, int>> myKeyValuePairList = new List<KeyValuePair<string, int>>();
myKeyValuePairList.Add(new KeyValuePair<string, int>("apple", 1));
myKeyValuePairList.Add(new KeyValuePair<string, int>("banana", 2));
myKeyValuePairList.Add(new KeyValuePair<string, int>("orange", 3));
foreach (KeyValuePair<string, int> kvp in myKeyValuePairList)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
Dictionary<string, int> myKeyValuePairDictionary = new Dictionary<string, int>();
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("apple", 1));
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("banana", 2));
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("orange", 3));
foreach (KeyValuePair<string, int> kvp in myKeyValuePairDictionary)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
這就是在C#中使用KeyValuePair的基本方法。您可以根據需要創建和使用自己的鍵值對集合。