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

C# 常用数据结构之字典Dictionary<TKey,TValue>

Dictionary<TKey,TValue> 是 C# 中使用非常频繁的一种数据结构,我们通常称之为“字典”!其中每个元素都是由键值对(Key-Value)组成!

命名空间:System.Collections.Generic

特性

1、键值对中的键和值都可以是任何类型的(泛型),但是键必须唯一且不能为 null,而值可以不唯一;

2、增删改查速度快,查找一个值的时间复杂度接近 O(1);

3、长度不固定,动态扩容;

4、比较消耗内存(以空间换时间);

初始化

1、Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有默认的初始容量并为键类型使用默认的相等比较器。

Dictionary<int, string> testDict = new Dictionary<int, string>();
testDict.Add(1, "a");
testDict.Add(2, "b");
testDict.Add(3, "c");
foreach (KeyValuePair<int, string> element in testDict)
{
    Console.WriteLine("{0} {1}", element.Key, element.Value);
}
/*
1 a
2 b
3 c
*/

2、Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有指定的初始容量并为键类型使用默认的相等比较器。

Dictionary<string, string> testDict = new Dictionary<string, string>(10);
testDict.Add("name", "fightsyj");
testDict.Add("id", "123123");
testDict.Add("score", "100");
foreach (KeyValuePair<string, string> kvp in testDict)
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}
/*
name fightsyj
id 123123
score 100
*/

ps

如果 Dictionary<TKey,TValue> 的大小是可以估算的,最好在初始化的时候指定容量,这样可以在添加元素的时候避免无意义的动态扩容,提高性能!

3、当然,我们最常用的初始化方式应该是:使用集合初始值设定项初始化字典

Dictionary<string, string> testDict = new Dictionary<string, string> {
    {"name", "fightsyj"},
    {"id", "123123"},
    {"score", "100"}
};
foreach (KeyValuePair<string, string> kvp in testDict)
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}
/*
name fightsyj
id 123123
score 100
*/

或者:

Dictionary<string, string> testDict = new Dictionary<string, string> {
    ["name"] = "fightsyj",
    ["id"] = "123123",
    ["score"] = "100"
};
foreach (KeyValuePair<string, string> kvp in testDict)
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}
/*
name fightsyj
id 123123
score 100
*/

常用属性

Count

获取包含在 Dictionary<TKey,TValue> 中的键/值对的数目。

Dictionary<int, string> testDict = new Dictionary<int, string> {
    [1] = "one",
    [2] = "two",
    [3] = "three"
};
Console.WriteLine("testDict 中元素(键值对)的数量为:{0}", testDict.Count);
// testDict 中元素(键值对)的数量为:3

Keys

获得一个包含 Dictionary<TKey,TValue> 中的键的集合。

Dictionary<int, string> testDict = new Dictionary<int, string> {
    [1] = "one",
    [2] = "two",
    [3] = "three"
};
foreach (object key in testDict.Keys)
{
    Console.Write(key + " ");
}
// 1 2 3

Values

获得一个包含 Dictionary<TKey,TValue> 中的值的集合。

Dictionary<int, string> testDict = new Dictionary<int, string> {
    [1] = "one",
    [2] = "two",
    [3] = "three"
};
foreach (object value in testDict.Values)
{
    Console.Write(value + " ");
}
// one two three

常用方法

Add

将指定的键和值添加到字典中。

Dictionary<string, int> testDict = new Dictionary<string, int>(5);
testDict.Add("张三", 99);
testDict.Add("李四", 95);
testDict.Add("王五", 98);
foreach (KeyValuePair<string, int> kvp in testDict)
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}
/*
张三 99
李四 95
王五 98
*/

ps

容量不够,会自动扩容。

Clear

将所有键和值从 Dictionary<TKey,TValue> 中移除,即清空字典。

Dictionary<string, int> testDict = new Dictionary<string, int> {
    ["张三"] = 99,
    ["李四"] = 95,
    ["王五"] = 98
};
Console.WriteLine("当前键值对数量为:{0}", testDict.Count);  // 当前键值对数量为:3
testDict.Clear();
Console.WriteLine("当前键值对数量为:{0}", testDict.Count);  // 当前键值对数量为:0

ContainsKey

确定是否 Dictionary<TKey,TValue> 包含指定键。

Dictionary<string, int> testDict = new Dictionary<string, int> {
    {"张三", 99},
    {"李四", 95},
    {"王五", 98},
};
Console.WriteLine(testDict.ContainsKey("王五"));  // True
Console.WriteLine(testDict.ContainsKey("赵六"));  // False

ContainsValue

确定 Dictionary<TKey,TValue> 是否包含特定值。

Dictionary<string, int> testDict = new Dictionary<string, int> {
    {"张三", 99},
    {"李四", 95},
    {"王五", 98},
};
Console.WriteLine(testDict.ContainsValue(99));  // True
Console.WriteLine(testDict.ContainsValue(100));  // False

Remove

将带有指定键的元素(键值对)从 Dictionary<TKey,TValue> 中移除。

Dictionary<string, string> testDict = new Dictionary<string, string> {
    ["name"] = "fightsyj",
    ["sex"] = "male",
    ["age"] = "guess"
};
testDict.Remove("sex");
foreach (KeyValuePair<string, string> kvp in testDict)
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}
// name fightsyj
// age guess
Console.WriteLine("当前键值对数量为:{0}", testDict.Count);  // 当前键值对数量为:2

TryGetValue

获取与指定键关联的值。

Dictionary<string, string> testDict = new Dictionary<string, string> {
    ["name"] = "fightsyj",
    ["sex"] = "male",
    ["age"] = "guess"
};
string value = "";
bool ret = testDict.TryGetValue("name", out value);  // 存在:true 不存在:false
Console.WriteLine("以 name 为键的键值对 {0},对应的值为:{1}", ret ? "存在" : "不存在", value);
// 以 name 为键的键值对 存在,对应的值为:fightsyj

参考:

Dictionary<TKey,TValue> 类

C#-字典<TKey,TValue>

相关文章:

  • 领导作为“先知者”需知的九大管理之道
  • C# 列表List<T>排序整理
  • 企业在经营时 要为自己“挖一口井”
  • C# 字典Dictionary<TKey,TValue>排序整理
  • 协同软件市场一盘散沙 春种能否秋收心中没底
  • bat 与或非
  • 独立软件开发商,出路何在?
  • Lua实战之不使用循环逆序输出一个数组
  • VS Code快速生成C#注释头
  • 10个装机最贵与免费的十大软件下载
  • VS 和 VS Code 更换字体
  • .NET值类型变量“活”在哪?
  • Lua do-end
  • VS Code 安装 VSIX 插件
  • 平台为王:Microsoft Office System为什么成功?
  • co模块的前端实现
  • css选择器
  • Docker下部署自己的LNMP工作环境
  • ECMAScript 6 学习之路 ( 四 ) String 字符串扩展
  • Javascript编码规范
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • maven工程打包jar以及java jar命令的classpath使用
  • Netty+SpringBoot+FastDFS+Html5实现聊天App(六)
  • PHP 程序员也能做的 Java 开发 30分钟使用 netty 轻松打造一个高性能 websocket 服务...
  • Webpack 4x 之路 ( 四 )
  • zookeeper系列(七)实战分布式命名服务
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 前端性能优化——回流与重绘
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 提醒我喝水chrome插件开发指南
  • 移动端解决方案学习记录
  • 原生JS动态加载JS、CSS文件及代码脚本
  • 在Unity中实现一个简单的消息管理器
  • 字符串匹配基础上
  • ​软考-高级-信息系统项目管理师教程 第四版【第23章-组织通用管理-思维导图】​
  • #预处理和函数的对比以及条件编译
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (C++17) std算法之执行策略 execution
  • (poj1.3.2)1791(构造法模拟)
  • (八)光盘的挂载与解挂、挂载CentOS镜像、rpm安装软件详细学习笔记
  • (二)springcloud实战之config配置中心
  • (分类)KNN算法- 参数调优
  • (附源码)springboot 房产中介系统 毕业设计 312341
  • (附源码)ssm教材管理系统 毕业设计 011229
  • (附源码)ssm跨平台教学系统 毕业设计 280843
  • (十七)Flask之大型项目目录结构示例【二扣蓝图】
  • (转)我也是一只IT小小鸟
  • (转载)CentOS查看系统信息|CentOS查看命令
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • *ST京蓝入股力合节能 着力绿色智慧城市服务
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .net core 调用c dll_用C++生成一个简单的DLL文件VS2008
  • .net 设置默认首页
  • .NET/C# 在 64 位进程中读取 32 位进程重定向后的注册表