C# 键值对

一、键值对的基本使用

1、增

cs 复制代码
  Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
  //创建键值对,键的类型为int 值的类型为decimal
  dic.Add(1, 2.5m);
  dic.Add(2, 3.7m);
  dic.Add(3, 4.2m);
 //添加三组数据

2、删

① 根据键值对中的键值删除某组数据

cs 复制代码
  Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
  //创建键值对,键的类型为int 值的类型为decimal

  dic.Add(1, 2.5m);
  dic.Add(2, 3.7m);
  dic.Add(3, 4.2m);

  bool b= dic.Remove(2); //移除键值对中键值为2的那组数据,如果没有找到,返回false

②删除键值对中全部数据(清空键值对)

cs 复制代码
  Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
  //创建键值对,键的类型为int 值的类型为decimal

  dic.Add(1, 2.5m);
  dic.Add(2, 3.7m);
  dic.Add(3, 4.2m);
  dic.Clear();  //移除所有的键和值

3、查

①使用foreach遍历整个键值对中全部数据

cs 复制代码
     Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
     //创建键值对,键的类型为int 值的类型为decimal

     dic.Add(1, 2.5m);
     dic.Add(2, 3.7m);
     dic.Add(3, 4.2m);

     foreach (KeyValuePair<int, decimal> kvp in dic)
     {
         Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
     }

②使用for循环遍历整个键值对中全部数据

cs 复制代码
   Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
   //创建键值对,键的类型为int 值的类型为decimal

   dic.Add(1, 2.5m);
   dic.Add(2, 3.7m);
   dic.Add(3, 4.2m);

   for (int i = 0; i < dic.Count; i++)
   {
       int key = dic.Keys.ElementAt(i);
       decimal value = dic[key];
   }
相关推荐
FAFU_kyp26 分钟前
Rust 的 引用与借用
开发语言·算法·rust
永远都不秃头的程序员(互关)27 分钟前
【K-Means深度探索(一)】数据炼金术第一步:从零手撕K-Means聚类算法
算法·kmeans·聚类
我想回家种地29 分钟前
算法期末复习
算法
该用户已不存在38 分钟前
不止是初始化,4个C# 构造函数解析与实例
后端·c#·.net
rgeshfgreh1 小时前
MPPI算法实战:运动规划新利器
算法
Xの哲學1 小时前
Linux epoll 深度剖析: 从设计哲学到底层实现
linux·服务器·网络·算法·边缘计算
小猪咪piggy1 小时前
【leetcode100】回溯
数据结构·算法
m0_603888711 小时前
More Images, More Problems A Controlled Analysis of VLM Failure Modes
人工智能·算法·机器学习·ai·论文速览
恶魔泡泡糖1 小时前
51单片机矩阵按键
c语言·算法·矩阵·51单片机
叶子2024221 小时前
电力系统分析---对称分量法
算法