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();
相关推荐
JosieBook10 分钟前
【WinForm】使用C# WinForm实现带有托盘图标功能的应用程序
开发语言·c#
缺点内向27 分钟前
在 C# 中为 Word 段落添加制表位:使用 Spire.Doc for .NET 实现高效排版
开发语言·c#·自动化·word·.net
老骥伏枥~1 小时前
【C# 入门】变量、常量与命名规范
开发语言·c#
A_nanda2 小时前
vue快速学习框架
前端·javascript·vue.js·学习·c#
Eiceblue3 小时前
通过 C# 解析 HTML:文本提取 + 结构化数据获取
c#·html·.net·visual studio
SunnyDays10113 小时前
使用 C# 将 Excel XLSX 或 XLS 转换为 HTML:完整指南
c#·excel转html·xlsx转html·xls转html
时光追逐者3 小时前
一款基于 .NET Avalonia 开源免费、快速、跨平台的图片查看器
c#·.net·图片查看器
阿蒙Amon18 小时前
C#每日面试题-Thread.Sleep和Task.Delay的区别
java·数据库·c#
cfqq198918 小时前
Settings,变量保存
开发语言·c#
云草桑19 小时前
.net AI开发04 第八章 引入RAG知识库与文档管理核心能力及事件总线
数据库·人工智能·microsoft·c#·asp.net·.net·rag