C# 中的键值对

王林
王林 转载
2023-08-25 22:49:02 562浏览

C# 中的键值对

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);
      }
   }
}

以上就是C# 中的键值对的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除