【转】Dictionary(数据字典)
原文地址:https://www.cnblogs.com/shanhuashuiqing11/p/6000468.html
数据字典:Dictionary对象用于在结对的名称/值中存储信息(等同于键和项目),其可作为传参使用。
//定义字典 Dictionary<string, string> d = new Dictionary<string, string>(); //添加字典的元素 for (int i = 0; i < 5; i++) { d.Add("key" + i, "value" + i); } //取值/赋值 string val = d["key1"]; d["key1"] = "new value"; //遍历key foreach (string key in d.Keys) { Console.WriteLine("Key = {0}", key); } //遍历value foreach (string v in d.Values) { Console.WriteLine("value = {0}", v); } //遍历value, Second Method Dictionary<string, string>.ValueCollection valueColl = d.Values; foreach (string s in valueColl) { Console.WriteLine("Second Method, Value = {0}", s); } //遍历字典 foreach (KeyValuePair<string, string> kvp in d) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } //删除元素 d.Remove("key1"); if (!d.ContainsKey("key1")) { Console.WriteLine("Key \"key1\" is not found."); } //判断键存在 if (d.ContainsKey("key1")) // True { Console.WriteLine("An element with Key = \"key1\" exists."); }
扩展:
当在字典中不能确定是否存在该键时需要使用TryGetValue,以减少一次不必要的查找,同时避免了判断Key值是否存在而引发的“给定关键字不在字典中。”的错误。(TryGetValue是根据ID返回相应的数据,如果没有ID则返回默认值)
myObject result = null; if (theDictionary.TryGetValue(id, out result)) {}

浙公网安备 33010602011771号