C# Dictionary 字典

转载至:C#中的Dictionary字典类介绍

1 命名空间与继承关系

命名空间:System.Collections.Generic
继承关系:
Object→Dictionary<TKey,TValue>
表示键和值的集合。

2 Dictionary 简介

(1)Dictionary包含的命名空间:System.Collection.Generic
(2)Dictionary元素都是由键值对组成
(3)键和值可以是任何类型(int,string,自定义等)

3 Dictionary使用方法

例:Dictionary<string,string> MyDt = new Dictionary<string,string>();

序号 方法/属性 说明
1 MyDt.Add(“1”,“a”) 添加一个元素
2 MyDt.Remove(“1”,“a”) 删除一个元素
3 MyDt[“1”] = “b” 修改一个元素值
4 string value = MyDt[“1”] 获取一个元素值/通过key查找元素
5 MyDt.ContainsKey(“2”) 判断键是否存在
6 MyDt.ContainsValue(“a”) 判断值是否存在
7 MyDt.Clear() 清空字典
8 MyDt.Count() 返回字典元素个数

4 Dictionary的遍历

遍历方法:①遍历Key;②遍历Value;③遍历Key-Value;

static void Main(string[] args)
{
      //创建一个字典
      Dictionary<int, string> MyDh = new Dictionary<int, string>();
      MyDh.Add(1, "aaa");
      MyDh.Add(2, "bbb");
      MyDh.Add(3, "ccc");
      MyDh.Add(4, "ddd");
      //遍历Key
      Console.WriteLine("遍历Key");
      foreach (int Key in MyDh.Keys)
      {
           Console.WriteLine(Key);
       }
       //遍历Value
       Console.WriteLine("遍历Value");
       foreach (string value in MyDh.Values)
       {
           Console.WriteLine(value);
        }
        //遍历Key-Value
        Console.WriteLine("遍历Key-Value");
        foreach (KeyValuePair<int, string> item in MyDh)
        {
           Console.WriteLine(item.Key + "\t" + item.Value);
        }
 }

结果如下:
在这里插入图片描述

5 其他套路

(1)添加已存在元素

try
{
    MyDh.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

(2)删除元素

 MyDh.Remove("doc");
 if (!MyDh.ContainsKey("doc"))
{
   Console.WriteLine("Key \"doc\" is not found.");
}

猜你喜欢

转载自blog.csdn.net/qq_29406323/article/details/86363637