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];
   }
相关推荐
Navigator_Z4 小时前
LeetCode //C - 1089. Duplicate Zeros
c语言·算法·leetcode
云泽8087 小时前
C++ 可调用对象通关指南:深度解析 Lambda 表达式、function 包装器与 bind 绑定器
开发语言·c++·算法
wlsh157 小时前
Go 迭代器
算法
语戚8 小时前
力扣 3161. 块放置查询:线段树解法(Java 实现)
java·算法·leetcode·面试·线段树·力扣·
CS创新实验室8 小时前
从顺序表到动态数组:数据结构的永恒基石与现代语言的优雅封装
数据结构·算法
Black蜡笔小新9 小时前
自动化AI算法训练服务器DLTM训推一体化平台助力农业生产管理实现安全智能化
人工智能·算法·自动化
8Qi810 小时前
LeetCode 23. 合并 K 个升序链表 —— 小顶堆(PriorityQueue)
数据结构·算法·leetcode·链表·
QiLinkOS10 小时前
《打破“用爱发电”:一种基于 Gitee 与时间戳的开源权益分配机制探索》
c语言·数据结构·c++·科技·算法·gitee·开源
松间听晚11 小时前
Agentic RL 环境和代码学习:以HGPO为例
算法