C#中Dictionary的用法

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

方法/步驟

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

     System.Collections.Generic(程序集:mscorlib)

  2.  Dictionary的描述

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

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

    3、鍵不能爲空引用null(VB中的Nothing),若值爲引用類型,則可以爲空值

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

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

     1、創建及初始化

     Dictionary<int,string>myDictionary=newDictionary<int,string>();

     

     2、添加元素

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

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

    myDictionary.Add(3,"ASP.NET");

    myDictionary.Add(4,"MVC");

     

     3、通過Key查找元素

    if(myDictionary.ContainsKey(1))

    {

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

     }

     

     4、通過KeyValuePair遍歷元素

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

    {

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

    }

     

    5、僅遍歷鍵 Keys 屬性

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

    foreach(intkeyinkeyCol)

    ...{

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

    }

     

    6、僅遍歷值 Valus屬性

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

    foreach(stringvalueinvalueCol)

    {

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

    }

     

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

    myDictionary.Remove(1);

    if(myDictionary.ContainsKey(1))

    {

      Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[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:      獲取與指定的鍵相關聯的值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章