C#中Dictionary(数据字典)的用法总结

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

例:
1、value为字符串值:Dictionary<string,string> MyDt = new Dictionary<string,string>();
2、value为对象值:Dictionary<string, List<object>> mylist_METER = new Dictionary<string, List<object>>();

image.png

3 Dictionary的遍历

遍历方法:①遍历Key;②遍历Value;③遍历Key-Value;
a、遍历string型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);
        }
 }

结果如下:


image.png

遍历object型value值

            //定义数据字典:Dictionary<键,值>
            Dictionary<string, List<object>> mylist_METERW = new Dictionary<string, List<object>>();
            Dictionary<string, List<object>> mylist_METER = new Dictionary<string, List<object>>();
            sqlite.GetSQL(sql_METER, out mylist_METER);

            Console.WriteLine("遍历Value22:" + mylist_METERW["standard"][1]);

            Console.WriteLine("遍历Key");
            foreach (string Key in mylist_METER.Keys)
            {
                Console.WriteLine(Key);
            }


            //遍历Key
            Console.WriteLine("遍历Key");
            foreach (string Key in mylist_METERW.Keys)
            {
                Console.WriteLine(Key);
            }
            //遍历Value
            Console.WriteLine("遍历Value");
            foreach (List<object> value in mylist_METERW.Values)
            {
                Console.WriteLine(value[0].ToString());
            }
            //遍历Key-Value
            Console.WriteLine("遍历Key-Value");
            foreach (KeyValuePair<string, List<object>> item in mylist_METERW)
            {
                Console.WriteLine(item.Key + "\t" + item.Value);
            }

4 其他用法

(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.");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容