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);
}
相关推荐
We་ct14 分钟前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮5 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说5 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove6 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung6 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了6 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL6 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰7 小时前
C++ 排列组合完整指南
开发语言·c++·算法
代码中介商7 小时前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法