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();
相关推荐
神仙别闹30 分钟前
基于C#+Mysql实现(界面)企业的设备管理系统
开发语言·mysql·c#
△曉風殘月〆4 小时前
.Net Gacutil工具(全局程序集缓存工具)使用教程
c#·.net·gac·gacutil
时光追逐者4 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 5 期(2024年9.9-9.15)
microsoft·c#·.net·.netcore
太陈抱不动8 小时前
C#学习笔记(三)Visual Studio安装与使用
笔记·学习·c#
秋月的私语8 小时前
C#通过注册表实现记住上次打开路径
c#·html·xhtml
Z_W_H_16 小时前
【C#】vs2022 .net8
c#
c#上位机21 小时前
C#回调函数
java·前端·c#
0224号比邻星1 天前
[C语言]第九节 函数一基础知识到高级技巧的全景探索
c语言·c#
△曉風殘月〆1 天前
C#命令行参数解析库System.CommandLine介绍
c#·命令行·cmd·命令行解析
阑梦清川1 天前
C#环境搭建和入门教程--vs2022之下
开发语言·c#