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];
   }
相关推荐
小羊在睡觉3 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary4 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
好评笔记4 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466854 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
周杰伦fans4 小时前
C# 踩坑 CS8370:Switch Expression 在 C# 7.3 不可用及三种解决方案
c#
_日拱一卒4 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM5 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro5 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言
voidmort6 小时前
3. 微调(Fine-tuning)与强化学习(RL)的核心思想
python·深度学习·算法
z落落6 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#