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);
}
相关推荐
何以解忧,唯有..13 分钟前
预订酒店问题
算法
No8g攻城狮22 分钟前
【算法】什么是 DFS 与 BFS 及他们的区别
算法·深度优先·宽度优先
zww894911130 分钟前
家政派单系统实战指南:从需求分析到智能调度算法落地
算法·需求分析
手写码匠43 分钟前
华为云Flexus+DeepSeek征文|Dify 多 Agent 评测实战:用 DeepSeek-R1 当裁判,打造多智能体系统的自动化质量保障体系
人工智能·深度学习·算法·aigc
ZC跨境爬虫1 小时前
LeetCode 88. 合并两个有序数组(双指针详解 + Java Python 实现)
java·python·算法·leetcode
Nil2081 小时前
leetcode 238除了自身以外数组的乘积
数据结构·算法·leetcode
土司大王1 小时前
LeetCode hot100——最长连续序列
数据结构·算法·leetcode
caimouse1 小时前
ReactOS 图形系统分析(17):区域填充 — EngPaint / IntEngPaint(paint.c)
c语言·开发语言·算法
生态学者1 小时前
Ecological Indicators | 机场鸟调的新方法:用 AWM-PC1 读懂干扰梯度下的鸟类群落
人工智能·算法·r语言·微信公众平台
Herbert_hwt1 小时前
第六章 Java深入理解接口、函数式接口与lambda表达式
java·开发语言·算法