using System; using System.Collections.Generic; using Newtonsoft.Json; namespace study_dictionary { class Program { static void Main(string[] args) { DictionaryStudy(); } /// <summary> /// ContainsKey: 确定 Dictionary是否包含指定的键。 /// ContainsValue: 确定 Dictionary是否包含特定值。 /// TryAdd: 存在添加不成功 /// </summary> static void DictionaryStudy() { //Dictionary<int, string> dictionaryTest = new Dictionary<int, string>() { { 1, "gyg" }, { 2, "gmd" } };//初始化不推荐 Dictionary<int, string> dictionaryTest = new Dictionary<int, string>(); dictionaryTest.Clear();//清空所有的键值 if (!dictionaryTest.ContainsKey(1))//防止报异常 { dictionaryTest.Add(1, "gyg"); } bool result = dictionaryTest.TryAdd(1, "gxh");//存在添加不成功 Console.WriteLine("TryAdd:" + result); //dictionaryTest.Add(1, "gmd");//这样会报异常 Console.WriteLine(dictionaryTest[1]);//取值 dictionaryTest[1] = "gmd";//索引方式赋值,没有则新增,有则修改 dictionaryTest[2] = "gyg"; dictionaryTest.Remove(2);//根据键删除 dictionaryTest.Add(3, "gxy"); dictionaryTest.Add(4, "gxy"); Console.WriteLine("count:" + dictionaryTest.Count); //遍历键值对 foreach (var kvp in dictionaryTest)//var => KeyValuePair<int, string> { Console.WriteLine("key:" + kvp.Key + "-value:" + kvp.Value); } //遍历键 //dictionaryTest.Keys => Dictionary<int, string>.KeyCollection foreach (int key in dictionaryTest.Keys) { Console.WriteLine("key:" + key); } //遍历值 Dictionary<int, string>.ValueCollection vc = dictionaryTest.Values; foreach (string value in vc) { Console.WriteLine("value:" + value); } string json = JsonConvert.SerializeObject(dictionaryTest); Console.WriteLine("json字符串:" + json); //Console.WriteLine(dictionaryTest[5]);//不存在的键会报异常 dictionaryTest.TryGetValue(5, out string value1); Console.WriteLine("TryGetValue:" + value1); } } }