C# System.Collections.Generic.Dictionary

  1 using System;
  2 using System.Collections.Generic;
  3 
  4 public class Example
  5 {
  6     public static void Main()
  7     {
  8         // Create a new dictionary of strings, with string keys.
  9         //
 10         Dictionary<string, string> openWith = 
 11             new Dictionary<string, string>();
 12 
 13         // Add some elements to the dictionary. There are no 
 14         // duplicate keys, but some of the values are duplicates.
 15         openWith.Add("txt", "notepad.exe");
 16         openWith.Add("bmp", "paint.exe");
 17         openWith.Add("dib", "paint.exe");
 18         openWith.Add("rtf", "wordpad.exe");
 19 
 20         // The Add method throws an exception if the new key is 
 21         // already in the dictionary.
 22         try
 23         {
 24             openWith.Add("txt", "winword.exe");
 25         }
 26         catch (ArgumentException)
 27         {
 28             Console.WriteLine("An element with Key = \"txt\" already exists.");
 29         }
 30 
 31         // The Item property is another name for the indexer, so you 
 32         // can omit its name when accessing elements. 
 33         Console.WriteLine("For key = \"rtf\", value = {0}.", 
 34             openWith["rtf"]);
 35 
 36         // The indexer can be used to change the value associated
 37         // with a key.
 38         openWith["rtf"] = "winword.exe";
 39         Console.WriteLine("For key = \"rtf\", value = {0}.", 
 40             openWith["rtf"]);
 41 
 42         // If a key does not exist, setting the indexer for that key
 43         // adds a new key/value pair.
 44         openWith["doc"] = "winword.exe";
 45 
 46         // The indexer throws an exception if the requested key is
 47         // not in the dictionary.
 48         try
 49         {
 50             Console.WriteLine("For key = \"tif\", value = {0}.", 
 51                 openWith["tif"]);
 52         }
 53         catch (KeyNotFoundException)
 54         {
 55             Console.WriteLine("Key = \"tif\" is not found.");
 56         }
 57 
 58         // When a program often has to try keys that turn out not to
 59         // be in the dictionary, TryGetValue can be a more efficient 
 60         // way to retrieve values.
 61         string value = "";
 62         if (openWith.TryGetValue("tif", out value))
 63         {
 64             Console.WriteLine("For key = \"tif\", value = {0}.", value);
 65         }
 66         else
 67         {
 68             Console.WriteLine("Key = \"tif\" is not found.");
 69         }
 70 
 71         // ContainsKey can be used to test keys before inserting 
 72         // them.
 73         if (!openWith.ContainsKey("ht"))
 74         {
 75             openWith.Add("ht", "hypertrm.exe");
 76             Console.WriteLine("Value added for key = \"ht\": {0}", 
 77                 openWith["ht"]);
 78         }
 79 
 80         // When you use foreach to enumerate dictionary elements,
 81         // the elements are retrieved as KeyValuePair objects.
 82         Console.WriteLine();
 83         foreach( KeyValuePair<string, string> kvp in openWith )
 84         {
 85             Console.WriteLine("Key = {0}, Value = {1}", 
 86                 kvp.Key, kvp.Value);
 87         }
 88 
 89         // To get the values alone, use the Values property.
 90         Dictionary<string, string>.ValueCollection valueColl =
 91             openWith.Values;
 92 
 93         // The elements of the ValueCollection are strongly typed
 94         // with the type that was specified for dictionary values.
 95         Console.WriteLine();
 96         foreach( string s in valueColl )
 97         {
 98             Console.WriteLine("Value = {0}", s);
 99         }
100 
101         // To get the keys alone, use the Keys property.
102         Dictionary<string, string>.KeyCollection keyColl =
103             openWith.Keys;
104 
105         // The elements of the KeyCollection are strongly typed
106         // with the type that was specified for dictionary keys.
107         Console.WriteLine();
108         foreach( string s in keyColl )
109         {
110             Console.WriteLine("Key = {0}", s);
111         }
112 
113         // Use the Remove method to remove a key/value pair.
114         Console.WriteLine("\nRemove(\"doc\")");
115         openWith.Remove("doc");
116 
117         if (!openWith.ContainsKey("doc"))
118         {
119             Console.WriteLine("Key \"doc\" is not found.");
120         }
121     }
122 }
123 
124 /* This code example produces the following output:
125 
126 An element with Key = "txt" already exists.
127 For key = "rtf", value = wordpad.exe.
128 For key = "rtf", value = winword.exe.
129 Key = "tif" is not found.
130 Key = "tif" is not found.
131 Value added for key = "ht": hypertrm.exe
132 
133 Key = txt, Value = notepad.exe
134 Key = bmp, Value = paint.exe
135 Key = dib, Value = paint.exe
136 Key = rtf, Value = winword.exe
137 Key = doc, Value = winword.exe
138 Key = ht, Value = hypertrm.exe
139 
140 Value = notepad.exe
141 Value = paint.exe
142 Value = paint.exe
143 Value = winword.exe
144 Value = winword.exe
145 Value = hypertrm.exe
146 
147 Key = txt
148 Key = bmp
149 Key = dib
150 Key = rtf
151 Key = doc
152 Key = ht
153 
154 Remove("doc")
155 Key "doc" is not found.
156  */

 

 1 using System;
 2 using System.Collections.Generic;
 3 public class Example
 4 {
 5          public static void Main()
 6          {
 7                //1、建立泛型哈希表,而後加入元素
 8                Dictionary<string, string> oscar = new Dictionary<string, string>();
 9                oscar.Add("哈莉?貝瑞", "《死囚之舞》");
10                oscar.Add("朱迪?丹奇", "《攜手人生》");
11                oscar.Add("尼科爾?基德曼", "《紅磨坊》");
12                oscar.Add("詹妮弗?康納利", "《美麗心靈》");
13                oscar.Add("蕾妮?齊維格", "《BJ單身日記》");
14 
15                //2、刪除元素
16                oscar.Remove("詹妮弗?康納利");
17 
18                //3、假如不存在元素則加入元素
19                if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不倫之戀》");
20                
21 
22                //4、顯然容量和元素個數
23                Console.WriteLine("元素個數: {0}", oscar.Count);
24 
25                //5、遍歷集合
26                Console.WriteLine("74屆奧斯卡最佳女主角及其電影:");
27                foreach (KeyValuePair<string, string> kvp in oscar)
28                {
29                       Console.WriteLine("姓名:{0},電影:{1}", kvp.Key, kvp.Value);
30                }
31 
32               //6、獲得哈希表中鍵的集合
33               Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
34               //遍歷鍵的集合
35               Console.WriteLine("最佳女主角:");
36               foreach (string s in keyColl)
37               {
38                    Console.WriteLine(s);
39               }
40 
41               //7、獲得哈希表值的集合
42               Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
43               //遍歷值的集合
44               Console.WriteLine("最佳女主角電影:");
45               foreach (string s in valueColl)
46               {
47                    Console.WriteLine(s);
48               }
49 
50               //8、使用TryGetValue方法獲取指定鍵對應的值
51               string slove = string.Empty;
52               if (oscar.TryGetValue("朱迪?丹奇", out slove))
53                      Console.WriteLine("我最喜歡朱迪?丹奇的電影{0}", slove);
54               else
55                      Console.WriteLine("沒找到朱迪?丹奇的電影");
56 
57               //9、清空哈希表
58               oscar.Clear();
59               Console.ReadLine();
60        }
61 }

 

 1 //定義字典
 2                 Dictionary<string, string> d = new Dictionary<string, string>();
 3 
 4                 //添加字典的元素
 5                 for (int i = 0; i < 5; i++)
 6                 {
 7                     d.Add("key" + i, "value" + i);
 8                 }
 9 
10                 //取值/賦值
11                 string val = d["key1"];
12                 d["key1"] = "new value";
13 
14                 //遍歷key
15                 foreach (string key in d.Keys)
16                 {
17                     Console.WriteLine("Key = {0}", key);
18                 }
19                 //遍歷value
20                 foreach (string v in d.Values)
21                 {
22                     Console.WriteLine("value = {0}", v);
23                 }
24 
25                 //遍歷value, Second Method
26                 Dictionary<string, string>.ValueCollection valueColl = d.Values;
27                 foreach (string s in valueColl)
28                 {
29                     Console.WriteLine("Second Method, Value = {0}", s);
30                 }
31 
32                 //遍歷字典
33                 foreach (KeyValuePair<string, string> kvp in d)
34                 {
35                     Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
36                 }
37                 //刪除元素
38                 d.Remove("key1");
39                 if (!d.ContainsKey("key1"))
40                 {
41                     Console.WriteLine("Key \"key1\" is not found.");
42                 }
43                 //判斷鍵存在
44                 if (d.ContainsKey("key1")) // True 
45                 {
46                     Console.WriteLine("An element with Key = \"key1\" exists.");
47                 }

 

構造函數 

Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 類的新實例,該實例爲空且具備默認的初始容量,並使用鍵類型的默認相等比較器。android

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

初始化 Dictionary<TKey,TValue> 類的新實例,該實例包含從指定的 IDictionary<TKey,TValue> 中複製的元素併爲鍵類型使用默認的相等比較器。ios

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 類的新實例,該實例包含從指定的 IDictionary<TKey,TValue> 中複製的元素並使用指定的 IEqualityComparer<T>api

Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 類的新實例,該實例爲空且具備默認的初始容量,並使用指定的 IEqualityComparer<T>app

Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 類的新實例,該實例爲空且具備指定的初始容量,併爲鍵類型使用默認的相等比較器。函數

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 類的新實例,該實例爲空且具備指定的初始容量,並使用指定的 IEqualityComparer<T>spa

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

用序列化數據初始化 Dictionary<TKey,TValue> 類的新實例。code

屬性 

Comparer

獲取用於肯定字典中的鍵是否相等的 IEqualityComparer<T>對象

Count

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

Item[TKey]

獲取或設置與指定的鍵關聯的值。接口

Keys

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

Values

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

方法 

Add(TKey, TValue)

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

Clear()

將全部鍵和值從 Dictionary<TKey,TValue> 中移除。

ContainsKey(TKey)

肯定是否 Dictionary<TKey,TValue> 包含指定鍵。

ContainsValue(TValue)

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

Equals(Object)

肯定指定的對象是否等於當前對象。

(Inherited from Object)
GetEnumerator()

返回循環訪問 Dictionary<TKey,TValue> 的枚舉數。

GetHashCode()

做爲默認哈希函數。

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

實現 ISerializable 接口,並返回序列化 Dictionary<TKey,TValue> 實例所需的數據。

GetType()

獲取當前實例的 Type

(Inherited from Object)
MemberwiseClone()

建立當前 Object 的淺表副本。

(Inherited from Object)
OnDeserialization(Object)

實現 ISerializable 接口,並在完成反序列化以後引起反序列化事件。

Remove(TKey)

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

ToString()

返回表示當前對象的字符串。

(Inherited from Object)
TryGetValue(TKey, TValue)

獲取與指定鍵關聯的值。

相關文章
相關標籤/搜索