C# 字典 Dictionary

Dictionary( TKey , TValue )算法

表示鍵和值的集合。code

Dictionary( TKey, TValue) 泛型類提供了從一組鍵到一組值的映射。字典中的每一個添加項都由一個值及其相關聯的鍵組成。經過鍵來檢索值的速度是很是快的,接近於 O(1),這是由於Dictionary( TKey, TValue) 類是做爲一個哈希表來實現的。(檢索速度取決於爲 TKey 指定的類型的哈希算法的質量。)對象

只要對象用做 Dictionary( TKey, TValue) 中的鍵,它就不能以任何影響其哈希值的方式更改。使用字典的相等比較器比較時,Dictionary( TKey, TValue) 中的任何鍵都必須是惟一的。鍵不能爲 null 。 可是若是值類型 TValue 爲引用類型,該值則能夠爲空。string

經常使用方法it

using System;
using System.Collections.Generic;
public class Example
{
         public static void Main()
         {
               //1、建立泛型哈希表,而後加入元素
               Dictionary<string, string> oscar = new Dictionary<string, string>();
               oscar.Add("哈莉?貝瑞", "《死囚之舞》");
               oscar.Add("朱迪?丹奇", "《攜手人生》");
               oscar.Add("尼科爾?基德曼", "《紅磨坊》");
               oscar.Add("詹妮弗?康納利", "《美麗心靈》");
               oscar.Add("蕾妮?齊維格", "《BJ單身日記》");

               //2、刪除元素
               oscar.Remove("詹妮弗?康納利");

               //3、假如不存在元素則加入元素
               if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不倫之戀》");
               

               //4、顯然容量和元素個數
               Console.WriteLine("元素個數: {0}", oscar.Count);

               //5、遍歷集合
               Console.WriteLine("74屆奧斯卡最佳女主角及其電影:");
               foreach (KeyValuePair<string, string> kvp in oscar)
               {
                      Console.WriteLine("姓名:{0},電影:{1}", kvp.Key, kvp.Value);
               }

              //6、獲得哈希表中鍵的集合
              Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
              //遍歷鍵的集合
              Console.WriteLine("最佳女主角:");
              foreach (string s in keyColl)
              {
                   Console.WriteLine(s);
              }

              //7、獲得哈希表值的集合
              Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
              //遍歷值的集合
              Console.WriteLine("最佳女主角電影:");
              foreach (string s in valueColl)
              {
                   Console.WriteLine(s);
              }

              //8、使用TryGetValue方法獲取指定鍵對應的值
              string slove = string.Empty;
              if (oscar.TryGetValue("朱迪?丹奇", out slove))
                     Console.WriteLine("我最喜歡朱迪?丹奇的電影{0}", slove);
              else
                     Console.WriteLine("沒找到朱迪?丹奇的電影");

              //9、清空哈希表
              oscar.Clear();
              Console.ReadLine();
       }
}
相關文章
相關標籤/搜索