C# 中的 Pair 类
csharpprogrammingserver side programming更新于 2025/8/12 5:37:17
Pair 类是 KeyValuePair 类,它在 C# 中将一对值存储在单个列表中。
声明 KeyValuePair −
var myList = new List<KeyValuePair>string, int>>();
Now, add some elements:
myList.Add(new KeyValuePair<string, int>("Laptop", 1));
myList.Add(new KeyValuePair<string, int>("Desktop System", 2));
myList.Add(new KeyValuePair<string, int>("Tablet", 3));
myList.Add(new KeyValuePair<string, int>("Mobile", 4));
myList.Add(new KeyValuePair<string, int>("E-Book Reader", 5));
myList.Add(new KeyValuePair<string, int>("LED", 6));
现在显示 KeyValuePair,如下所示 −
示例
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<string, int>>();
// 添加元素
myList.Add(new KeyValuePair <string, int>("Laptop", 1));
myList.Add(new KeyValuePair <string, int>("Desktop System", 2));
myList.Add(new KeyValuePair <string, int>("Tablet", 3));
myList.Add(new KeyValuePair <string, int>("Mobile", 4));
myList.Add(new KeyValuePair <string, int>("E-Book Reader", 5));
myList.Add(new KeyValuePair <string, int>("LED", 6));
foreach (var val in myList) {
Console.WriteLine(val);
}
}
}
输出
[Laptop, 1] [Desktop System, 2] [Tablet, 3] [Mobile, 4] [E-Book Reader, 5] [LED, 6]

