Dictionary用法詳解


1  Dictionary

(1) 表示鍵和值的集合.

(2)類型參數:

TKey   字典中的鍵的類型

TValue 字典中的值的類型

(3)Dictionary 泛型類提供了從一組鍵到一組值的映射。字典中的每個添加項都由一個值及其相關聯的鍵組成。通過鍵來檢索值的速度是非常快的,接近於 O(1),這是因為 Dictionary 類是作為一個哈希表來實現的。

(4)定義:

Dictionary<string, string> openWith = new Dictionary<string, string>();

(5)使用Add方法可以向其中添加值

openWith.Add("txt", "notepad.exe");

當添加重復的鍵時會引發ArgumentException類型的異常。

(6)使用["txt"]的方法可以找到相對應的值,並可以修改這個鍵對應的值。

如果鍵不存在,可以通過如下方法添加新的鍵/值對。

openWith["doc"] = "winword.exe";

如果取值的鍵不存在,會引發一個KeyNotFoundException類型的異常。

(7)使用TryGetValue方法來嘗試取出一個鍵對應的值,如果這個值存在就取出返回,這樣可以避免拋出KeyNotFoundException異常。返回值類型為布爾類型。

(8)使用ContainsKey方法來判斷是否包含指定的鍵,返回值類型為布爾類型。

(9)使用foreach遍歷:

foreach (KeyValuePair<string, string> kvp in openWith)
            {
                Console.WriteLine("Key = {0}, Value = {1}",
                    kvp.Key, kvp.Value);
            }

(10)使用Values屬性,可以僅取出所有的值而不取出所有的鍵。

 Dictionary<string, string>.ValueCollection valuecol = openWith.Values;

foreach (string str in valuecol)
      Console.WriteLine(str);

 

(11)使用Keys屬性,可以僅取出所有的鍵而不取出所有的值。

(12)使用Remove方法,可以根據鍵來移除集合中的鍵/值對。

openWith.Remove("jin");當移除值的時候同時移除鍵。

2  實例程序

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys.
        //
        Dictionary<string, string> openWith = 
            new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the dictionary.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is another name for the indexer, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", 
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", 
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        Dictionary<string, string>.ValueCollection valueColl =
            openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM