C#中的Dictionary简介

本文介绍了C#中Dictionary的基本用法,包括创建、添加、查找和删除键值对的操作,并展示了如何处理不存在的键异常及如何使用其他类型的键。
简介
在C#中,Dictionary提供快速的基于兼职的元素查找。当你有很多元素的时候可以使用它。它包含在System.Collections.Generic名空间中。

在使用前,你必须声明它的键类型和值类型。

详细说明
必须包含名空间System.Collection.Generic
Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
键必须是唯一的,而值不需要唯一的
键和值都可以是任何类型(比如:string, int, 自定义类型,等等)
通过一个键读取一个值的时间是接近O(1)
键值对之间的偏序可以不定义
创建和初始化一个Dictionary对象
Dictionary myDictionary = new Dictionary();
添加键
static void Main(string[] args)
{
  Dictionary d = new Dictionary();
  d.Add("C#", 2);
  d.Add("C", 0);
  d.Add("C++", -1);
}
查找键
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add("C#", 2);
   d.Add("VB", 1);
   d.Add("C", 0);
   d.Add("C++", -1);
   if (d.ContainsKey("VB")) // True
   {
      int p = d["VB"];
      Console.WriteLine(p);
     } 
 
     if (d.ContainsKey("C"))
     {
       int p1 = d["C"];
       Console.WriteLine(p1);
     }
}
删除元素
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add("C#", 2);
   d.Add("VB", 1);
   d.Add("C", 0);
   d.Add("C++", -1);
 
   d.Remove("C");    
   d.Remove("VB");
}
使用ContainsValue查找值的存在
static void Main(string[] args)
{
    Dictionary d = new Dictionary();
    d.Add("C#", 2);
    d.Add("VB", 1);
    d.Add("C", 0);
    d.Add("C++", -1);
    if (d.ContainsValue(1))
    {
        Console.WriteLine("VB");
    }
    if (d.ContainsValue(2))
    {
       Console.WriteLine("C#");
    }
    if (d.ContainsValue(0))
    {
       Console.WriteLine("C");
    }
    if (d.ContainsValue(-1))
      {
          Console.WriteLine("C++");
      }               
}
KeyNotFoundException
如果你尝试读取字典中一个不存在的键,那么你会得到一个KeyNotFoundException。所有在读取一个键之前,你必须先使用ContainKey来核对键是否存在字典中。

基于int键的Dictionary
static void Main(string[] args)
{
   Dictionary d = new Dictionary();
   d.Add(1000, "Planet");
   d.Add(2000, "Stars");
   // lookup the int in the dictionary.
   if (d.ContainsKey(1000))
   {
        Console.WriteLine(true);
   }
      Console.ReadLine();
}
排序字典SortedDictionary
在排序字典中,当添加元素时字典必须进行排序,所以插入的速度会比较慢点。但是因为元素是有序存储的,所以元素的查找可以使用二分搜索等一些效率更高的搜索。

总结
在这篇文章中,简要地介绍C#中的Dictionary的使用。动手写写吧~

  1. using System;  
  2. using System.Collections.Generic;  
  3.  
  4. class DictionaryDemo  
  5. {  
  6.     static void Main(string[] args)  
  7.     {  
  8.         DictionaryDemo001();  
  9.         Console.ReadLine();  
  10.  
  11.         DictionaryDemo002();  
  12.         Console.ReadLine();  
  13.  
  14.         DictionaryDemo003();  
  15.         Console.ReadLine();  
  16.     }  
  17.  
  18.     /// <summary>  
  19.     /// 一般用法  
  20.     /// </summary>  
  21.     static void DictionaryDemo001()  
  22.     {  
  23.         Dictionary<int, string> dict = new Dictionary<int, string>();  
  24.         dict.Add(1, "111");  
  25.         dict.Add(2, "222");  
  26.  
  27.         //判断是否存在相应的key并显示  
  28.         if (dict.ContainsKey(2))  
  29.         {  
  30.             Console.WriteLine(dict[2]);  
  31.         }  
  32.  
  33.         //遍历Keys  
  34.         foreach (var item in dict.Keys)  
  35.         {  
  36.             Console.WriteLine("Key:{0}", item);  
  37.         }  
  38.  
  39.         //遍历Values  
  40.         foreach (var item in dict.Values)  
  41.         {  
  42.             Console.WriteLine("value:{0}", item);  
  43.         }  
  44.  
  45.         //遍历整个字典  
  46.         foreach (var item in dict)  
  47.         {  
  48.             Console.WriteLine("key:{0} value:{1}", item.Key, item.Value);  
  49.         }  
  50.     }  
  51.  
  52.     /// <summary>  
  53.     /// 参数为其它类型  
  54.     /// </summary>  
  55.     static void DictionaryDemo002()  
  56.     {  
  57.         Dictionary<string, string[]> dict = new Dictionary<string, string[]>();  
  58.         dict.Add("1", "1,11,111".Split(','));  
  59.         dict.Add("2", "2,22,222".Split(','));  
  60.         Console.WriteLine(dict["2"][2]);  
  61.     }  
  62.  
  63.     /// <summary>  
  64.     /// 调用自定义类  
  65.     /// </summary>  
  66.     static void DictionaryDemo003()  
  67.     {  
  68.         Dictionary<int, yongfa365> dict = new Dictionary<int, yongfa365>();  
  69.         for (int i = 0; i < 10; i++)  
  70.         {  
  71.             yongfa365 y = new yongfa365();  
  72.             y.UserCode = i;  
  73.             y.UserName = "www.yongfa365.com " + i.ToString();  
  74.             dict.Add(i, y);  
  75.         }  
  76.         foreach (var item in dict)  
  77.         {  
  78.             Console.WriteLine("{0} One:{1} UserName:{2}", item.Key, item.Value.UserCode, item.Value.UserName);  
  79.         }  
  80.     }  
  81. }  
  82.  
  83. class yongfa365  
  84. {  
  85.     public int UserCode { get; set; }  
  86.     public string UserName { get; set; }  
  87.  
<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`,操作前需检查键是否存在
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值