当前位置: 首页 > backend >正文

C#拾遗补漏之 Dictionary 详解

基本概念

Dictionary<TKey, TValue>是C#中用于存储键值对集合的泛型类,属于System.Collections.Generic命名空间。它允许使用键(Key)来访问与其关联的值(Value)。其中,TKey表示字典中键的类型,TValue表示字典中值的类型。

Dictionary的基本结构

  • 键(Key):唯一标识集合中的一个元素。键是唯一的,不能有重复。

  • 值(Value):与键相关联的数据。值可以是任意类型,并且可以有重复。

  • 键值对(KeyValuePair):键和值的组合,表示Dictionary中的一个元素。

Dictionary的主要特性

  • 快速访问:通过键可以快速检索到对应的值,平均时间复杂度接近O(1),因为Dictionary<TKey,TValue>类是作为哈希表实现。

  • 唯一键(Key):每个键在Dictionary中都是唯一的,不能重复。

  • 动态大小:Dictionary的大小可以动态调整,当元素数量超过容量时,它会自动扩容。

  • 无序集合:Dictionary中的元素是无序的,不能通过索引来访问它们。

Dictionary的常用操作

以下是C#中Dictionary的常用操作完整代码,其中包括添加元素、访问元素、修改元素、删除元素、检查键或值是否存在,以及遍历元素:

public static void DictionaryOperation()
{//创建一个Dictionary来存储学生学号ID和姓名Dictionary<int, string> studentDic = new Dictionary<int, string>();#region 添加元素// Add方法(键必须唯一)studentDic.Add(1, "大姚");studentDic.Add(2, "小袁");studentDic.Add(3, "Edwin");// 索引器语法(键不存在时添加,存在时更新)studentDic[4] = "Charlie";studentDic[5] = "追逐时光者";// 安全添加(避免异常)bool isAdded = studentDic.TryAdd(6, "小明"); // 返回 false,因键已存在#endregion#region 访问元素// 直接访问(键必须存在,否则会有异常)var currentUserName = studentDic[1];Console.WriteLine($"当前学生姓名: {currentUserName}");// 安全访问(避免异常)if (studentDic.TryGetValue(5, outvar getUserName)){Console.WriteLine($"UserName:{getUserName}");}else{Console.WriteLine("当前学生ID不存在");}#endregion#region// 修改元素studentDic[2] = "大西瓜";Console.WriteLine($"修改后的名称:{studentDic[2]}");#endregion#region 删除元素// 删除元素bool isRemoved = studentDic.Remove(3);Console.WriteLine($"删除结果:{isRemoved}");#endregion#region 检查键或值是否存在// 检查键是否存在if (studentDic.ContainsKey(1)){Console.WriteLine("存在");}else{Console.WriteLine("不存在");}bool isExistcontainsValue = studentDic.ContainsValue("追逐时光者");Console.WriteLine($"是否存在:{isExistcontainsValue}");#endregion#region 遍历元素// 遍历元素foreach (KeyValuePair<int, string> student in studentDic){Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");}// 使用键的枚举器foreach (var key in studentDic.Keys){Console.WriteLine($"Key: {key}, Value: {studentDic[key]}");}// 使用值的枚举器foreach (varvaluein studentDic.Values){// 注意:这种方式不能直接获取键,只能获取值Console.WriteLine($"Value: {value}");}#endregion
}

参考文章

  • https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2?view=net-9.0

http://www.xdnf.cn/news/8830.html

相关文章:

  • 【从0到1搞懂大模型】chatGPT 中的对齐优化(RLHF)讲解与实战(9)
  • uniapp报错mongo_cell_decision_not_found
  • Python年快乐!祝福语大全。
  • 从零开始:Python语言进阶之迭代器
  • JVM——JNI 的运行机制
  • Python模型优化技巧
  • Unity基础学习(九)Resources资源同步与异步加载
  • C++23内存分配新特性:std::allocate_at_least
  • JavaWeb:SpringBoot实现简单用户登录JWT用户鉴权
  • string的使用和模拟实现
  • Redis哨兵模式,CLUSTERDOWN Hash slot not server 解决
  • 大数据模型对陌生场景图像的识别能力研究 —— 以 DEEPSEEK 私有化部署模型为例
  • NestJS——重构日志、数据库、配置
  • CMake从入门到实战:现代C++项目构建指南
  • Linux--vim
  • 超简单Translation翻译模型部署
  • TCP/IP
  • Mac系统-最方便的一键环境部署软件ServBay(支持php,java,python,node,go,mysql等)没有之一,已亲自使用!
  • RocketMQ 5.0 核心概念与架构解析
  • 深入剖析 RocketMQ:消息保障、事务处理与负载均衡策略
  • Lua 脚本在 Redis 中的运用-24 (使用 Lua 脚本实现原子计数器)
  • SpringBoot返回xml
  • NV171NV173美光闪存颗粒NV181NV186
  • binlog解析工具——binlog2sql
  • 动态规划(6)下降路径最小值
  • C++ for QWidget:类(1)
  • 22、web场景-web开发简介
  • Java 内部类
  • Php JIT 使用详解
  • 慢查询日志的开启与分析:优化SQL性能的实战指南