欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Dictionary的基本用法

程序员文章站 2023-11-10 22:03:52
1.创建泛型哈希表,然后加入元素 Dictionary openWith=new Dictionary(); openWith.Add("txt","notepad.exe"); openWith.Add("bmp","paint.exe ......

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");

2.遍历key

    foreach (string key in openwith.keys)
            {
                console.writeline("key = {0}", key);
            }

3.遍历value

 foreach (string value in openwith.values)
            {
                console.writeline("value = {0}", value);
            }

4.遍历value, second method

 

dictionary<string, string>.valuecollection valuecoll = openwith.values;
            foreach (string s in valuecoll)
            {
                console.writeline("second method, value = {0}", s);
            }

 

5.遍历字典

 

foreach (keyvaluepair<string, string> kvp in openwith)
            {
                console.writeline("key = {0}, value = {1}", kvp.key, kvp.value);
            }

 

6.添加存在的元素

 

try
            {
                openwith.add("txt", "winword.exe");
            }
            catch (argumentexception)
            {
                console.writeline("an element with key = \"txt\" already exists.");
            }

 

7.删除元素

openwith.remove("doc");
            if (!openwith.containskey("doc"))
            {
                console.writeline("key \"doc\" is not found.");
            }

8.判断键存在

if (openwith.containskey("bmp")) // true 
            {
                console.writeline("an element with key = \"bmp\" exists.");
            }

9.参数为其它类型

 

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]);