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 //一、创建泛型哈希表,然后加入元素 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 //二、删除元素 16 oscar.Remove("詹妮弗?康纳利"); 17 18 //三、假如不存在元素则加入元素 19 if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不伦之恋》"); 20 21 22 //四、显然容量和元素个数 23 Console.WriteLine("元素个数: {0}", oscar.Count); 24 25 //五、遍历集合 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 //六、得到哈希表中键的集合 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 //七、得到哈希表值的集合 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 //八、使用TryGetValue方法获取指定键对应的值 51 string slove = string.Empty; 52 if (oscar.TryGetValue("朱迪?丹奇", out slove)) 53 Console.WriteLine("我最喜欢朱迪?丹奇的电影{0}", slove); 54 else 55 Console.WriteLine("没找到朱迪?丹奇的电影"); 56 57 //九、清空哈希表 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> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。 |
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。 |
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) |
初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 IEqualityComparer<T>。 |
Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用指定的 IEqualityComparer<T>。 |
Dictionary<TKey,TValue>(Int32) |
初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。 |
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并使用指定的 IEqualityComparer<T>。 |
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。 |
属性
Comparer |
获取用于确定字典中的键是否相等的 IEqualityComparer<T>。 |
Count |
获取包含在 Dictionary<TKey,TValue> 中的键/值对的数目。 |
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) |
获取与指定键关联的值。 |