C# 中的 KeyValuePair

csharpprogrammingserver side programming更新于 2025/8/11 23:37:17

C# 中的 KeyValuePair 类用于将一对值存储在单个列表中。

设置 KeyValuePair 并添加元素 −

var myList = new List<KeyValuePair<string, int>>();

// 添加元素
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>>();
      // 添加元素
      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);
      }
   }
}

相关文章