[转] C#中的Dictionary的使用

本文详细介绍了C#中Dictionary类的基本概念、使用方法及常见属性和方法。包括如何定义、添加、读取、更新和遍历Dictionary中的元素。此外还演示了如何处理不同类型的键和值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

txw1958 的 原文

说明
    必须包含名空间System.Collection.Generic 
    Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值) 
    键必须是唯一的,而值不需要唯一的 
    键和值都可以是任何类型(比如:string, int, 自定义类型,等等) 
    通过一个键读取一个值的时间是接近O(1) 
    键值对之间的偏序可以不定义

使用方法

    //定义
    Dictionary<string, string> openWith = new Dictionary<string, string>();

 

    //添加元素
    openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe");

 

    //取值
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

 

    //更改值
    openWith["rtf"] = "winword.exe"; Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

 

复制代码
    //遍历key
    foreach (string key in openWith.Keys) { Console.WriteLine("Key = {0}", key); }
复制代码

 

复制代码
复制代码
    //遍历value
    foreach (string value in openWith.Values) { Console.WriteLine("value = {0}", value); } //遍历value, Second Method Dictionary<string, string>.ValueCollection valueColl = openWith.Values; foreach (string s in valueColl) { Console.WriteLine("Second Method, Value = {0}", s); }
复制代码
复制代码

 

    //遍历字典
    foreach (KeyValuePair<string, string> kvp in openWith) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); }

 

复制代码
复制代码
    //添加存在的元素
    try
    {
        openWith.Add("txt", "winword.exe"); } catch (ArgumentException) { Console.WriteLine("An element with Key = \"txt\" already exists."); }
复制代码
复制代码

 

复制代码
    //删除元素
    openWith.Remove("doc"); if (!openWith.ContainsKey("doc")) { Console.WriteLine("Key \"doc\" is not found."); }
复制代码

 

    //判断键存在
    if (openWith.ContainsKey("bmp")) // True  { Console.WriteLine("An element with Key = \"bmp\" exists."); }

 

参数为其它类型

    //参数为其它类型 
    Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>(); OtherType.Add(1, "1,11,111".Split(',')); OtherType.Add(2, "2,22,222".Split(',')); Console.WriteLine(OtherType[1][2]);

 

参数为自定义类型

首先定义类

复制代码
    class DouCube
    {
        public int Code { get { return _Code; } set { _Code = value; } } private int _Code; public string Page { get { return _Page; } set { _Page = value; } } private string _Page; } 
复制代码

然后

复制代码
复制代码
    //声明并添加元素
    Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>(); for (int i = 1; i <= 9; i++) { DouCube element = new DouCube(); element.Code = i * 100; element.Page = "http://www.doucube.com/" + i.ToString() + ".html"; MyType.Add(i, element); }
复制代码
复制代码
复制代码
    //遍历元素
    foreach (KeyValuePair<int, DouCube> kvp in MyType) { Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page); } 
复制代码

 

 

常用属性

    名称    说明
    Comparer     获取用于确定字典中的键是否相等的 IEqualityComparer<T>。
    Count        获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。
    Item         获取或设置与指定的键相关联的值。
    Keys         获取包含 Dictionary<TKey, TValue> 中的键的集合。
    Values       获取包含 Dictionary<TKey, TValue> 中的值的集合。

常用方法
    名称    说明
    Add                 将指定的键和值添加到字典中。
    Clear               从 Dictionary<TKey, TValue> 中移除所有的键和值。
    ContainsKey         确定 Dictionary<TKey, TValue> 是否包含指定的键。
    ContainsValue       确定 Dictionary<TKey, TValue> 是否包含特定值。
    Equals(Object)      确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
    Finalize            允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
    GetEnumerator       返回循环访问 Dictionary<TKey, TValue> 的枚举器。
    GetHashCode         用作特定类型的哈希函数。 (继承自 Object。)
    GetObjectData       实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary<TKey, TValue> 实例所需的数据。
    GetType             获取当前实例的 Type。 (继承自 Object。)
    MemberwiseClone     创建当前 Object 的浅表副本。 (继承自 Object。)
    OnDeserialization    实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
    Remove              从 Dictionary<TKey, TValue> 中移除所指定的键的值。
    ToString            返回表示当前对象的字符串。 (继承自 Object。)
    TryGetValue         获取与指定的键相关联的值。

 

 

 

 

没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。






  本文转自wenglabs博客园博客,原文链接:http://www.cnblogs.com/arxive/p/5795423.html,如需转载请自行联系原作者

<think>我们正在回答用户关于C#Dictionary使用方法的请求。用户要求提供示例。根据引用内容,我们可以总结出以下关键点:1. Dictionary是泛型类,用于存储键值对,键必须唯一。2.创建Dictionary使用`Dictionary<TKey, TValue>`并初始化。3.添加元素:使用Add方法,注意键不能重复,否则会抛出异常。4.访问元素:通过键来访问值,如`dict[key]`,如果键不存在会抛出异常。5.检查键是否存在:使用ContainsKey方法。6.安全获取值:使用TryGetValue方法,避免键不存在时的异常。7.删除元素:使用Remove方法。8.遍历Dictionary:可以使用foreach循环,遍历KeyValuePair。我们将按照以下结构组织回答:1.创建Dictionary2.添加元素3.访问元素4.检查键是否存在5.安全获取值(TryGetValue)6.删除元素7.遍历Dictionary8.其他注意事项(如初始化器、容量等)同时,我们将提供示例代码,并确保代码格式正确(使用代码块)。最后,生成相关问题。注意:引用内容中提供了一些示例,我们可以参考并整合。</think>### C# Dictionary 使用方法详解 `Dictionary<TKey, TValue>` 是 C# 中高效的键值对集合,适用于快速查找场景。以下是核心用法和示例: #### 1. **创建与初始化** ```csharp // 创建空字典 Dictionary<string, int> scores = new Dictionary<string, int>(); // 使用集合初始化器 Dictionary<string, string> countries = new Dictionary<string, string>() { {"CN", "中国"}, {"US", "美国"}, {"JP", "日本"} }; ``` #### 2. **添加元素** ```csharp scores.Add("Alice", 90); // 标准添加 scores["Bob"] = 85; // 索引器添加(若键存在则更新值) // 安全添加(避免重复键异常) if (!scores.ContainsKey("Charlie")) { scores.Add("Charlie", 75); } ``` #### 3. **访问元素** ```csharp // 直接访问(键不存在会抛异常) int aliceScore = scores["Alice"]; // 安全访问(推荐) if (scores.TryGetValue("Bob", out int bobScore)) { Console.WriteLine($"Bob's score: {bobScore}"); } else { Console.WriteLine("Key not found"); } ``` #### 4. **删除元素** ```csharp scores.Remove("Alice"); // 删除指定键 scores.Clear(); // 清空字典 ``` #### 5. **遍历字典** ```csharp foreach (KeyValuePair<string, int> kvp in scores) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } // 单独遍历键或值 foreach (string name in scores.Keys) { ... } foreach (int score in scores.Values) { ... } ``` #### 6. **常用方法** ```csharp bool hasAlice = scores.ContainsKey("Alice"); // 检查键 bool hasScore90 = scores.ContainsValue(90); // 检查值 int count = scores.Count; // 获取元素数量 ``` #### 7. **注意事项** - **键唯一性**:重复添加相同键会触发 `ArgumentException`[^5] - **空键禁止**:键不能为 `null`(值可为 `null`) - **性能优化**:预估容量时建议初始化指定大小,减少扩容开销 ```csharp var largeDict = new Dictionary<int, string>(capacity: 1000); ``` > 示例:检测键是否存在(引用自示例[^4]) > ```csharp > if (!countries.ContainsKey("USA")) > { > Console.WriteLine("Key USA is absent"); > } > ``` --- ### 相关问题 1. `Dictionary` 与 `Hashtable` 在 C# 中的主要区别是什么? 2. 如何实现线程安全的 `Dictionary` 操作? 3. `TryGetValue` 相比直接访问 `dict[key]` 有哪些性能优势? 4. 当字典的键是自定义类型时需要如何重写方法? 5. `ConcurrentDictionary` 在并发场景下提供了哪些特殊功能? [^1]: Dictionary 实现了 `IDictionary<TKey, TValue>` 接口,支持键值对存储 [^2]: 声明语法为 `Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>()` [^3]: Dictionary 是无序集合,键必须唯一 [^4]: 使用 `ContainsKey` 方法检测键是否存在 [^5]: 添加重复键会抛出 `ArgumentException`,操作前需检查键是否存在
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值