Dictionary摘抄

Dictionary,字典,键值对集合。

下面的代码示例创建一个空的带有字符串键的字符串 Dictionary,并使用 Add 方法添加一些元素。该示例演示在尝试添加重复的键时 Add 方法引发ArgumentException

该示例使用 Item 属性(在 C# 中为 索引器)来检索值,演示当请求的键不存在时将引发 KeyNotFoundException,并演示与键相关联的值可被替换。

该示例演示当程序必须经常尝试字典中不存在的键值时,如何使用 TryGetValue 方法作为一种更有效的方法来检索值,它还演示如何使用ContainsKey 方法在调用 Add 方法之前测试某个键是否存在。

该示例演示如何枚举字典中的键和值,以及如何分别使用 Keys 属性和 Values 属性来单独枚举键和值。

最后,该示例演示 Remove 方法。

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        //创建一个字典,键是字符串类型,值是字符串类型。
        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");

        // 如果新键已经在字典中,则添加方法将引发异常。
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("该键名已经在字典中存在");
        }

        // 可以直接通过:字典对象名["键名称"] 访问该键对应的值。
        Console.WriteLine(" value = {0}", openWith["rtf"]);

       

        // 可以通过给键重新赋值来改变键的值
        openWith["rtf"] = "winword.exe";
        Console.WriteLine(" key = "rtf", value = {0}.",openWith["rtf"]);
      
       // 如果键名在字典集合中不存在,赋值时就新建。
        openWith["doc"] = "winword.exe";
        Console.WriteLine(" key = "doc",value ={0}", openWith["doc"]);
      
     // 如果请求的键不在字典中,则抛出异常。
     try
     {
         Console.WriteLine("For key = "tif", value = {0}.",openWith["tif"]);
     }
     catch (KeyNotFoundException)
     {
         Console.WriteLine("Key = "tif" is not found.");
     }

       //当一个程序经常要获取键对应的值时,用TryGetValue获取与指定的键相关联的值效率高。
        string value = "";
     if (openWith.TryGetValue("txt", out value))
     {
         Console.WriteLine("For key = "txt", value = {0}.", value);
     }
     else
     {
         Console.WriteLine("Key = "tif" is not found.");
     }


        //  用ContainsKey测试是否包含指定的键
        if (!openWith.ContainsKey("ht"))
       {
            Console.WriteLine("不包含,我想创建");
           openWith.Add("ht", "hypertrm.exe");
           Console.WriteLine("Value added for key = "ht": {0}",openWith["ht"]);
       }


        //当使用foreach遍历字典中元素时,元素检索KeyValuePair对象
        foreach (KeyValuePair<string, string> kvp in openWith)

        {
            Console.WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        } 
        //普通遍历
        //foreach (var kvp in openWith)
        //{
        //    Console.WriteLine("Key = {0}, Value = {1}",
        //      kvp.Key, kvp.Value);
        //}



        //要获得单独的值,使用值属性
         Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
         Console.WriteLine();//输出空行
        //遍历输出,注意valueColl是强类型,要使用匹配的类型。 使用var未定义类型也可以输出。
        foreach (string s in valueColl)
        {
            Console.WriteLine("Value = {0}", s);
        }

        // 要获得单独的键,使用键属性
        Dictionary<string, string>.KeyCollection keyColl =openWith.Keys;
        Console.WriteLine();
       //遍历输出
      foreach (string s in keyColl)
      {
          Console.WriteLine("Key = {0}", s);
      }


   
        // 使用Remove方法移除键值对
        Console.WriteLine("
Remove("doc")");
        openWith.Remove("doc");

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

        Console.ReadKey();
    }
}


  

 
System.Object 
  System.Collections.Generic.Dictionary
原文地址:https://www.cnblogs.com/hao-1234-1234/p/6112457.html