C# 中的 KeyValuePair
KeyValuePair 类使用 C# 将一对值存储在一个列表中。
设置 KeyValuePair 并添加元素 −
var myList = new List<KeyValuePair<string, int>>(); // adding elements myList.Add(new KeyValuePair<string, int>("Laptop", 20)); myList.Add(new KeyValuePair<string, int>("Desktop", 40)); myList.Add(new KeyValuePair<string, int>("Tablet", 60));
以下代码演示了如何使用 KeyValuePair 以及如何显示键和值 −
示例
Using System; using System.Collections.Generic; class Program { static void Main() { var myList = new List<KeyValuePair<string, int>>(); // adding elements myList.Add(new KeyValuePair<string, int>("Laptop", 20)); myList.Add(new KeyValuePair<string, int>("Desktop", 40)); myList.Add(new KeyValuePair<string, int>("Tablet", 60)); foreach (var val in myList) { Console.WriteLine(val); } } }
广告