C#中Dictionary的用法


 在C#中,Dictionary提供快速的基於兼職的元素查找。他的結構是這樣的:Dictionary<[key], [value]> ,當你有很多元素的時候可以使用它。它包含在System.Collections.Generic名空間中。在使用前,你必須聲明它的鍵類型和值類型。

  1. 要使用Dictionary類,需要導入C#泛型命名空間

     System.Collections.Generic(在mscorlib.dll 中)

     

  2.  Dictionary的描述

    1、從一組鍵(Key)到一組值(Value)的映射,每一個添加項都是由一個值及其相關連的鍵組成

    2、任何鍵都必須是唯一的

    3、鍵不能為空引用null,若值為引用類型,則可以為空值

    4、Key和Value可以是任何類型(string,int,custom class 等)

     

  3.  Dictionary常用用法:以 key 的類型為 int , value的類型為string 為例

     

     1、創建及初始化

     Dictionary<int,string> DemoDictionary= new Dictionary<int,string>();

     

     2、添加元素

    DemoDictionary.Add(1,"C#");

    DemoDictionary.Add(2,"C++");

    DemoDictionary.Add(3,"Java");

    DemoDictionary.Add(4,"PHP");

     

     3、通過Key查找元素

    if(DemoDictionary.ContainsKey(1))

    {

    Console.WriteLine("Key:{0},Value:{1}","1", DemoDictionary[1]);

     }

     

     4、通過KeyValuePair遍歷元素

    foreach(KeyValuePair<int,string> kvp in DemoDictionary)

    {

    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);

    }

     

    5、僅遍歷鍵 Keys 屬性

    Dictionary<int,string>.KeyCollection keyCol=DemoDictionary.Keys;

    foreach(int key in keyCol)

    {

    Console.WriteLine("Key = {0}", key);

    }

     

    6、僅遍歷值 Valus屬性

    Dictionary<int,string>.ValueCollection valueCol=DemoDictionary.Values;

    foreach(string value in valueCol)

    {

    Console.WriteLine("Value = {0}", value);

    }

     

    7、通過Remove方法移除指定的鍵值

    DemoDictionary.Remove(1);

    if(DemoDictionary.ContainsKey(1))

    {

      Console.WriteLine("Key:{0},Value:{1}","1", DemoDictionary[1]);

    }

    else

    {

    Console.WriteLine("不存在 Key : 1"); 

     }

     

  4. 其它常見屬性和方法的說明:

     

      Comparer:           獲取用於確定字典中的鍵是否相等的 IEqualityComparer。

      Count:                  獲取包含在 Dictionary中的鍵/值對的數目。

      Item:                    獲取或設置與指定的鍵相關聯的值。

      Keys:                   獲取包含 Dictionary中的鍵的集合。

      Values:                獲取包含 Dictionary中的值的集合。

      Add:                    將指定的鍵和值添加到字典中。

      Clear:                  從 Dictionary中移除所有的鍵和值。

      ContainsKey:      確定 Dictionary是否包含指定的鍵。

      ContainsValue:   確定 Dictionary是否包含特定值。             

      GetEnumerator:  返回循環訪問 Dictionary的枚舉數。

      GetType:             獲取當前實例的 Type。 (從 Object 繼承。)

      Remove:             從 Dictionary中移除所指定的鍵的值。

      ToString:             返回表示當前 Object的 String。 (從 Object 繼承。)

      TryGetValue:      獲取與指定的鍵相關聯的值。


免責聲明!

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



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