溫馨提示×

c# keyvaluepair如何使用

c#
小樊
81
2024-11-20 06:26:09
欄目: 編程語言

在C#中,KeyValuePair是一個(gè)用于存儲(chǔ)鍵值對(duì)的無序集合。它位于System.Collections.Generic命名空間中。要使用KeyValuePair,首先需要?jiǎng)?chuàng)建一個(gè)KeyValuePair對(duì)象,然后將其添加到集合中,例如List或Dictionary。

以下是如何在C#中使用KeyValuePair的示例:

  1. 導(dǎo)入必要的命名空間:
using System;
using System.Collections.Generic;
  1. 創(chuàng)建一個(gè)KeyValuePair對(duì)象并將其添加到List中:
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));
  1. 遍歷List并訪問鍵值對(duì):
foreach (KeyValuePair<string, int> kvp in myKeyValuePairList)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
  1. 創(chuàng)建一個(gè)Dictionary并使用KeyValuePair對(duì)象:
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));
  1. 遍歷Dictionary并訪問鍵值對(duì):
foreach (KeyValuePair<string, int> kvp in myKeyValuePairDictionary)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}

這就是在C#中使用KeyValuePair的基本方法。您可以根據(jù)需要?jiǎng)?chuàng)建和使用自己的鍵值對(duì)集合。

0