C#Dicitionary

概念

Dicitionary 可以理解为拥有泛型的Hasntable

它也是基于键的哈希代码组织起来的,键/值对

键值对类型从Hashtable的object变为了可以自己定制的泛型

声明

cs 复制代码
Dictionary<int, string> dictionary = new Dictionary<int, string>();

增

不能出现相同键

cs 复制代码
dictionary.Add(1, "123");
dictionary.Add(2, "123");

删

对于不存在的键,那就不会有任何处理,不报错

cs 复制代码
dictionary.Remove(1);
dictionary.Remove(4);

清空

cs 复制代码
dictionary.Clear();
dictionary.Add(1, "123");
dictionary.Add(2, "123");

查

cs 复制代码
Console.WriteLine(dictionary[2]);
Console.WriteLine(dictionary[4]);

对于不存在的键,查找就直接报错

根据键检测

cs 复制代码
if (dictionary.ContainsKey(1))
{
    Console.WriteLine("存在");//
}

根据值检测

cs 复制代码
if (dictionary.ContainsValue("123"))
{
    Console.WriteLine("存在");//

}

改

cs 复制代码
dictionary[1] = "555";

遍历

遍历所有键

cs 复制代码
foreach(int item in dictionary.Keys)
{
    Console.WriteLine(item);
    Console.WriteLine(dictionary[item]);
}

遍历所有值

cs 复制代码
foreach(string item in dictionary.Values)//根据键去找值
{
    Console.WriteLine(item);
}
foreach(KeyValuePair<int,string>item in dictionary)
{
    Console.WriteLine("键" + item.Key + "值" + item.Value);
}
相关推荐
高晶9 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy9 小时前
大数计算思路
算法
高晶9 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗9 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李9 小时前
反向传播计算梯度举例
算法
niyongsheng9 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger10 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw0511 小时前
微分与积分的本质区别解析
算法·数学建模·极限编程
xys_67811 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
Interview Aid11212 小时前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法