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();
相关推荐
Iotfsd5 小时前
.NET写的开源工业物联网网关(IoTGateway)
物联网·c#·.net·dotnet·边缘网关·雾计算·工业物联网智能网关
先生沉默先5 小时前
c#接口_抽象类_多态学习
开发语言·学习·c#
江沉晚呤时5 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
iReachers6 小时前
使用命令行加密混淆C#程序
开发语言·c#
[太阳]886 小时前
Kafka命令行的使用/Spark-Streaming核心编程(二)
c#·linq
电商api接口开发19 小时前
ASP.NET MVC 入门指南
c#·asp.net·mvc
我不是程序猿儿20 小时前
[C#]反射的实战应用,实际数据模拟
开发语言·c#
爱编程的鱼20 小时前
C# 结构(Struct)
开发语言·人工智能·算法·c#
是阿根21 小时前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
ABAP 成1 天前
.NET Framework 4.0可用EXCEL导入至DataTable
c#