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);
}
相关推荐
不会就选b5 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
波力海苔夹心脆6757 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
千里码aicood8 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
做cv的小昊9 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له9 小时前
World-In-World: World Models in a Closed-Loop World
算法
Discipline102912 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder12 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!12 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
weixin_3077791312 小时前
基于睿擎工业开发平台的预训练视觉模型轻量化适配与低代码部署优化
开发语言·算法