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];
   }
相关推荐
lisw055 分钟前
微分与积分的本质区别解析
算法·数学建模·极限编程
xys_67842 分钟前
深挖数据结构:树和二叉树(上)
数据结构·算法
Interview Aid1121 小时前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法
波力海苔夹心脆6751 小时前
VisionMaster 两级位置修正实战:塑料外壳与金属件装配角度检测
经验分享·计算机视觉·c#·visionmaster·海康机器人·位置修正
琳达爱分享2 小时前
从单机令牌桶到集群限流:一次配额超发的复盘
后端·算法
range2 小时前
带TTL的LRU缓存的实现-字节手撕-26/10/19
算法
糖果豆豆2 小时前
n log n 到底从哪来?排序下界、2-SAT 与 3-SAT、停机问题,卡的是同一件事
算法·架构
地平线开发者2 小时前
【玩转 征程6 算法工具链:PTQ 工具篇】hb_verifier
算法·自动驾驶
171320330计算机毕设编程2 小时前
计算机毕业设计 基于springboot+vue的在线观鸟视频播放网站 LW PPT
java·大数据·vue.js·spring boot·算法·课程设计
himobrinehacken2 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全