c# 关于 Dictionary 知识点基础讲解

在C#中,Dictionary 是一种集合类型,用于存储键值对(key-value pairs)。它属于 System.Collections.Generic 命名空间,并提供了一种快速查找数据的方法。Dictionary 类似于哈希表或映射,允许你通过键(key)快速访问值(value)。

主要概念和特性

  1. 键值对Dictionary 中的每个元素都是一个键值对,键是唯一的,而值可以是任何类型。
  2. 泛型Dictionary<TKey, TValue> 是泛型集合,允许你指定键和值的类型。
  3. 快速查找Dictionary 使用哈希表实现,因此在大多数情况下,查找、插入和删除操作的时间复杂度接近 O(1)。
  4. 无序Dictionary 中的元素是无序的,如果你需要保持元素的顺序,可以考虑使用其他数据结构,如 ListSortedDictionary

声明和初始化

你可以通过以下几种方式声明和初始化一个 Dictionary

cs 复制代码
using System;  
using System.Collections.Generic;  
  
class Program  
{  
    static void Main()  
    {  
        // 创建一个字典,键为整数,值为字符串  
        Dictionary<int, string> dictionary = new Dictionary<int, string>();  
        dictionary.Add(1, "One");  
        dictionary.Add(2, "Two");  
        dictionary.Add(3, "Three");  
  
        // 使用 foreach 循环遍历字典  
        foreach (KeyValuePair<int, string> kvp in dictionary)  
        {  
            // kvp.Key 获取键,kvp.Value 获取值  
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);  
        }  
    }  
}

常用操作

  1. 添加元素

|---|-------------------------------|
| | dictionary1.Add(4, "Four"); |

  1. 访问元素

|---|--------------------------------------------|
| | string value = dictionary1[2]; // 通过键访问值 |

  1. 检查键是否存在

|---|--------------------------------------------------|
| | bool containsKey = dictionary1.ContainsKey(1); |

  1. 检查值是否存在

|---|----------------------------------------------------------|
| | bool containsValue = dictionary1.ContainsValue("Two"); |

  1. 移除元素

|---|-----------------------------------|
| | dictionary1.Remove(3); // 通过键移除 |

  1. 遍历元素

|---|----------------------------------------------------------------|
| | foreach (KeyValuePair<int, string> kvp in dictionary1) |
| | { |
| | Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}"); |
| | } |

示例代码

以下是一个完整的示例,展示了 Dictionary 的基本用法:

cs 复制代码
using System;  
using System.Collections.Generic;  
  
class Program  
{  
    static void Main()  
    {  
        // 初始化一个 Dictionary  
        Dictionary<int, string> dictionary = new Dictionary<int, string>  
        {  
            { 1, "One" },  
            { 2, "Two" },  
            { 3, "Three" }  
        };  
  
        // 添加新的键值对  
        dictionary.Add(4, "Four");  
  
        // 访问并打印元素  
        foreach (KeyValuePair<int, string> kvp in dictionary)  
        {  
            Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");  
        }  
  
        // 检查键是否存在  
        if (dictionary.ContainsKey(2))  
        {  
            Console.WriteLine("Dictionary contains key 2.");  
        }  
  
        // 移除元素  
        dictionary.Remove(3);  
  
        // 打印移除后的元素  
        Console.WriteLine("After removal:");  
        foreach (KeyValuePair<int, string> kvp in dictionary)  
        {  
            Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");  
        }  
    }  
}

KeyValuePair 是一种在 .NET 框架中定义的结构,用于表示一个键值对(Key-Value Pair)。它主要用于集合中,比如字典(Dictionary<TKey, TValue>),以便能够同时访问键(Key)和值(Value)。KeyValuePair 是一种泛型结构,定义在 System.Collections.Generic 命名空间中。

在C#中,$符号用于字符串插值(String Interpolation),它允许你在字符串中嵌入变量或表达式,并且这些变量或表达式会在运行时被其值所替换。这种方式使得字符串的格式化变得更加简洁和直观。

  • $ 符号告诉编译器,这是一个插值字符串。
  • {kvp.Key}{kvp.Value} 是插值表达式,它们会在运行时被 kvp.Keykvp.Value 的实际值所替换。
相关推荐
还在忙碌的吴小二11 分钟前
Harness 最佳实践:Java Spring Boot 项目落地 OpenSpec + Claude Code
java·开发语言·spring boot·后端·spring
liliangcsdn11 分钟前
mstsc不在“C:\Windows\System32“下在C:\windows\WinSxS\anmd64xxx“问题分析
开发语言·windows
小陈工22 分钟前
2026年4月7日技术资讯洞察:下一代数据库融合、AI基础设施竞赛与异步编程实战
开发语言·前端·数据库·人工智能·python
KAU的云实验台25 分钟前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆32 分钟前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
jerryinwuhan42 分钟前
RDD第二次练习
开发语言·c#
wechat_Neal1 小时前
Golang的车载应用场景
开发语言·后端·golang
weixin_513449961 小时前
walk_these_ways项目学习记录第八篇(通过行为多样性 (MoB) 实现地形泛化)--策略网络
开发语言·人工智能·python·学习
飞Link1 小时前
逆向兼容的桥梁:3to2 自动化降级工具实现全解析
运维·开发语言·python·自动化
曾阿伦2 小时前
Python3 文件 (夹) 操作备忘录
开发语言·python