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();
相关推荐
工程师0076 分钟前
C#反射的概念与实战
开发语言·c#·反射
embrace9941 分钟前
【C语言学习】scanf函数
c语言·开发语言·汇编·学习·青少年编程·c#·编辑器
唐青枫4 小时前
C#.NET 主机详解
c#·.net
R-G-B10 小时前
【28】C# WinForm入门到精通 ——多文档窗体MDI【属性、方法、实例、源码】【多窗口重叠、水平平铺、垂直平铺、窗体传值】
c#·winform·多文档窗体mdi·多窗口重叠·水平平铺·垂直平铺·窗体传值
LZQqqqqo14 小时前
c#_文件的读写 IO
开发语言·c#
CodeCraft Studio18 小时前
图像处理控件Aspose.Imaging教程:使用 C# 编程将 CMX 转换为 PNG
图像处理·人工智能·c#·aspose·png·图片格式转换·cmx
csdn_aspnet19 小时前
C# 求梯形面积的程序(Program to find area of a Trapezoid)
c#
LZQqqqqo20 小时前
C#_创建自己的MyList列表
java·算法·c#
lzhdim1 天前
C#开发的Panel里控件拖放例子 - 开源研究系列文章
开发语言·开源·c#
★YUI★1 天前
学习游戏制作记录(冻结敌人时间与黑洞技能)7.30
学习·游戏·unity·c#