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();
相关推荐
张人玉17 小时前
WPF 数据绑定与转换器详解
c#·wpf·light
主宰者18 小时前
WPF CalcBinding简化判断逻辑
c#·.net·wpf
就是有点傻1 天前
使用PaddleOCRSharp大模型精选文字识别
c#
LeonDL1681 天前
【通用视觉框架】基于C#+Winform+OpencvSharp开发的视觉框架软件,全套源码,开箱即用
人工智能·c#·winform·opencvsharp·机器视觉软件框架·通用视觉框架·机器视觉框架
数据的世界011 天前
技术变革:为何C#与.NET是未来的开发方向
java·c#·.net
大龄Python青年1 天前
C#快入教程:Linux安装.NET
linux·c#·.net
我是唐青枫1 天前
C#.NET Random 深入解析:随机数生成原理与最佳实践
c#·.net
光头闪亮亮1 天前
电子发票解析工具-c#桌面应用开发案例详解
c#
咕白m6251 天前
如何通过 C# 提取 PDF 图片?单页与全文档提取
c#·.net
时光追逐者1 天前
【拾遗补漏】.NET 常见术语集
微软·c#·.net