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];
   }
相关推荐
liliangcsdn1 分钟前
多空价差收益序列汇总统计的分析和代码示例
人工智能·算法·机器学习
啥都想学点的研究生8 分钟前
一篇文章讲清楚:Adaboost算法与GBDT
人工智能·算法
旖旎夜光17 分钟前
LeetCode 525:连续数组(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
zander25834 分钟前
LeetCode 32. 最长有效括号
算法
lvwangshu1 小时前
AC 自动机
算法·字符串
曹牧1 小时前
C#:线程间操作无效,不是从创建控件线程访问
开发语言·c#
anlog9 小时前
ini文件读取,EXE同目录文件读取
c#·ini
rockey62710 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
shehuiyuelaiyuehao10 小时前
算法31,前缀和,可被k整除的子数组
数据结构·python·算法
203号居民12 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表