Dictionary 基本運用 Dictionary 基本運用
  .NET       ez      2011-12-01

Dictionary 泛型類別提供從一組索引鍵至一組值的對應。

加入字典中的每一個項目都是由值及其關聯索引鍵所組成。

使用其索引鍵擷取值的速度非常快 (接近 O(1)),這是因為 Dictionary 類別是實作為雜湊資料表。

擷取速度取決於為 TKey 指定之型別的雜湊演算法品質。

只要物件用做 Dictionary 中的索引鍵,就無法以影響其雜湊值 (Hash Value) 的任何方式對其進行變更。

Dictionary 中的每個索引鍵都必須是唯一的 (根據字典的相等比較子 (Comparer))。

索引鍵不能是 Null 參照 (即 Visual Basic 中的 Nothing),但是,如果值型別 TValue 是參考型別時,值就可以是 Null。

using System;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //產生Dictionary
            Dictionary<string, string> D0 = new Dictionary<string, string>();

            //產生Dictionary並帶入值
            Dictionary<string, string> D = new Dictionary<string, string>()
            {
                { "a" , "1" } ,
                { "b" , "2" } ,
                { "c" , "3" }
            };

            //加入值
            D.Add("d", "4");

            //取得值
            string value = D["a"];

            //修改值
            D["a"] = "1";

            //刪除值
            D.Remove("d");

            //判斷索引是否存在
            if (D.ContainsKey("a"))
                Console.WriteLine("Value = " + D["a"]);
            else
                Console.WriteLine("Key is not found.");

            Console.ReadLine();
        }
    }
}

標籤:   .NET

我要留言