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);
}
相关推荐
通信小呆呆7 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
benben0447 小时前
强化学习之DQN算法族(基于gymnasium开发)
算法
何以解忧,唯有..8 小时前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
想吃火锅10059 小时前
【leetcode】88.合并两个有序数组js
算法
生成论实验室10 小时前
机器人:一个自主运动的系统
人工智能·算法·语言模型·机器人·自动驾驶·agi·安全架构
Qres82110 小时前
算法复键——树状数组
数据结构·算法
H1785350909610 小时前
SolidWorks第四部分_直接实体建模特征9_替换面原理
线性代数·算法·机器学习·3d建模·solidworks
不会就选b10 小时前
算法日常・每日刷题--<二分查找>3
算法
2601_9620725510 小时前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos