C#初级——字典Dictionary

字典

字典是C#中的一种集合,它存储键值对,并且每个键与一个值相关联。

创建字典

Dictionary<键的类型, 值的类型> 字典名字 = new Dictionary<键的类型, 值的类型>();

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

字典基本操作

添加元素

cs 复制代码
            dicStudent.Add(2, "张三");
            dicStudent.Add(5, "李四");
            dicStudent.Add(8, "王五");

访问元素

字典名键名;

cs 复制代码
Console.WriteLine(dicStudent[5]);

检查键是否存在

cs 复制代码
            if (dicStudent.ContainsKey(1))
            {
                Console.WriteLine("键存在");
            }
            else
            {
                Console.WriteLine("键不存在");
            }
            if (dicStudent.ContainsKey(2))
            {
                Console.WriteLine("键存在");
            }
            else
            {
                Console.WriteLine("键不存在");
            }

字典容量

cs 复制代码
            int count = dicStudent.Count;
            Console.WriteLine(count);

遍历字典

cs 复制代码
            foreach (KeyValuePair<int, string> item in dicStudent)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }

为了简化字典遍历的写法使用 var 代替 KeyValuePair<int, string> 类型。

cs 复制代码
            foreach (var item in dicStudent)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }

删除元素

cs 复制代码
            dicStudent.Remove(5);         //移除5键这个键值对
            foreach (var item in dicStudent)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }

获取键的列表

cs 复制代码
            var keys = dicStudent.Keys;
            foreach (var key in keys)
            {
                Console.WriteLine(key);
            }

获取值的列表

cs 复制代码
            var values = dicStudent.Values;
            foreach (var value in values)
            {
                Console.WriteLine(value);
            }

清空字典

cs 复制代码
            dicStudent.Clear();
相关推荐
北域码匠7 小时前
高通滤波算法深度解析(High-Pass Filter)
stm32·算法·c#·数字信号处理·嵌入式开发·滤波算法·高通滤波
rockey6279 小时前
C#脚本引擎之AScript与Z.Expressions.Eval对比
c#·.net·script·expression·动态脚本
天下无敌笨笨熊12 小时前
C#Modbus串口开发心得
开发语言·c#
CSDN_RTKLIB12 小时前
const与readonly关键字
c#
leonkay12 小时前
C# 锁机制——【2】深入原理
开发语言·后端·spring·c#·个人开发
geovindu17 小时前
CSharp: Wordcloud
开发语言·后端·c#·.net·.netcore·词云
geovindu18 小时前
CSharp: Command Pattern
开发语言·后端·c#·.net·.netcore·命令模式·行为模式
格林威21 小时前
C# 相机图像阴影校正:使用OpenCvSharp实现工业相机阴影平场校正功能
人工智能·数码相机·opencv·计算机视觉·c#·机器视觉·工业相机
俊昭喜喜里21 小时前
c#中的构造函数
开发语言·数据库·c#
hahaha601621 小时前
HLS高层次综合设计--axi之burst纠偏
开发语言·算法·fpga开发·c#