c# Dictionary字典类如何使用

    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);
            }
            //遍历字典
            foreach (KeyValuePair<string, string> kvp in openWith)
            {
                Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            }
            Console.WriteLine("===============");
            //删除元素
            openWith.Remove("rtf");
            //遍历字典
            foreach (KeyValuePair<string, string> kvp in openWith)
            {
                Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            }

  

posted on 2017-02-23 16:41  防空洞123  阅读(311)  评论(0编辑  收藏  举报

导航