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();
相关推荐
gc_22999 分钟前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty273 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机6 小时前
wpf之TextBlock
c#·wpf
almighty2716 小时前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty2716 小时前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
程序猿多布17 小时前
Lua和C#比较
c#·lua
csdn_aspnet1 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
csdn_aspnet1 天前
使用 C# .NETCore 实现MongoDB
mongodb·c#·.netcore
上位机付工1 天前
上位机通信速度有多快?
开发语言·c#·上位机·plc