天天看點

C# Dictionary字典類介紹

說明

    必須包含名空間System.Collection.Generic 

    Dictionary裡面的每一個元素都是一個鍵值對(由二個元素組成:鍵和值) 

    鍵必須是唯一的,而值不需要唯一的 

    鍵和值都可以是任何類型(比如:string, int, 自定義類型,等等) 

    通過一個鍵讀取一個值的時間是接近O(1) 

    鍵值對之間的偏序可以不定義

使用方法:

1    //定義
 2     Dictionary<string, string> openWith = new Dictionary<string, string>();
 3  
 4 
 5     //添加元素
 6     openWith.Add("txt", "notepad.exe");
 7     openWith.Add("bmp", "paint.exe");
 8     openWith.Add("dib", "paint.exe");
 9     openWith.Add("rtf", "wordpad.exe");
10  
11 
12     //取值
13     Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
14  
15 
16     //更改值
17     openWith["rtf"] = "winword.exe";
18     Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
19  
20 
21     //周遊key
22     foreach (string key in openWith.Keys)
23     {
24         Console.WriteLine("Key = {0}", key);
25     }
26  
27 
28 29     //周遊value
30     foreach (string value in openWith.Values)
31     {
32         Console.WriteLine("value = {0}", value);
33     }
34 
35     //周遊value, Second Method
36     Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
37     foreach (string s in valueColl)
38     {
39         Console.WriteLine("Second Method, Value = {0}", s);
40     }
41 42  
43 
44     //周遊字典
45     foreach (KeyValuePair<string, string> kvp in openWith)
46     {
47         Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
48     }
49  
50 
51 52     //添加存在的元素
53     try
54     {
55         openWith.Add("txt", "winword.exe");
56     }
57     catch (ArgumentException)
58     {
59         Console.WriteLine("An element with Key = \"txt\" already exists.");
60     }
61 62  
63 
64 65     //删除元素
66     openWith.Remove("doc");
67     if (!openWith.ContainsKey("doc"))
68     {
69         Console.WriteLine("Key \"doc\" is not found.");
70     }
71 72  
73 
74     //判斷鍵存在
75     if (openWith.ContainsKey("bmp")) // True 
76     {
77         Console.WriteLine("An element with Key = \"bmp\" exists.");
78     }      

參數為其它類型

1    //參數為其它類型 
2     Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();
3     OtherType.Add(1, "1,11,111".Split(','));
4     OtherType.Add(2, "2,22,222".Split(','));
5     Console.WriteLine(OtherType[1][2]);      

參數為自定義類型

首先定義類

1     class DouCube
2     {
3         public int Code { get { return _Code; } set { _Code = value; } } private int _Code;
4         public string Page { get { return _Page; } set { _Page = value; } } private string _Page;
5     }       

然後

1    //聲明并添加元素
 2     Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>();
 3     for (int i = 1; i <= 9; i++)
 4     {
 5         DouCube element = new DouCube();
 6         element.Code = i * 100;
 7         element.Page = "http://www.doucube.com/" + i.ToString() + ".html";
 8         MyType.Add(i, element);
 9     }
10 11     //周遊元素
12     foreach (KeyValuePair<int, DouCube> kvp in MyType)
13     {
14         Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
15     }       

常用屬性

    名稱    說明

    Comparer     擷取用于确定字典中的鍵是否相等的 IEqualityComparer<T>。

    Count        擷取包含在 Dictionary<TKey, TValue> 中的鍵/值對的數目。

    Item         擷取或設定與指定的鍵相關聯的值。

    Keys         擷取包含 Dictionary<TKey, TValue> 中的鍵的集合。

    Values       擷取包含 Dictionary<TKey, TValue> 中的值的集合。

常用方法

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

    Clear               從 Dictionary<TKey, TValue> 中移除所有的鍵和值。

    ContainsKey         确定 Dictionary<TKey, TValue> 是否包含指定的鍵。

    ContainsValue       确定 Dictionary<TKey, TValue> 是否包含特定值。

    Equals(Object)      确定指定的 Object 是否等于目前的 Object。 (繼承自 Object。)

    Finalize            允許對象在“垃圾回收”回收之前嘗試釋放資源并執行其他清理操作。 (繼承自 Object。)

    GetEnumerator       傳回循環通路 Dictionary<TKey, TValue> 的枚舉器。

    GetHashCode         用作特定類型的哈希函數。 (繼承自 Object。)

    GetObjectData       實作 System.Runtime.Serialization.ISerializable 接口,并傳回序列化 Dictionary<TKey, TValue> 執行個體所需的資料。

    GetType             擷取目前執行個體的 Type。 (繼承自 Object。)

    MemberwiseClone     建立目前 Object 的淺表副本。 (繼承自 Object。)

    OnDeserialization    實作 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之後引發反序列化事件。

    Remove              從 Dictionary<TKey, TValue> 中移除所指定的鍵的值。

    ToString            傳回表示目前對象的字元串。 (繼承自 Object。)

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