using System.Collections.Generic; namespace Lesson8_Dictionary { internal class Program { static void Main(string[] args) { #region 知识点一 Dictionary本质 //可以将Dictionary理解为 拥有泛型的Hashtable //他也是极于剑的哈希代码组织起来的 键/值对 //键值对类型从Hashtable的object变为了可以自己指定的泛型 #endregion #region 知识点二 声明 Dictionary dictionary = new Dictionary(); #endregion #region 知识点三 增删查改 #region 增 //注意:不能出现相同键 dictionary.Add(1, "111"); dictionary.Add(2, "222"); dictionary.Add(3, "333"); #endregion #region 删 //1.只能通过键去删除 // 删除不存在的键 无反应 dictionary.Remove(1); dictionary.Remove(4); //2.清空 dictionary.Clear(); #endregion #region 查 //1.通过键查看值 //注意:找不到直接报错,而不是像hashtable一样无反应 dictionary.Add(1, "111"); dictionary.Add(2, "222"); dictionary.Add(3, "333"); Console.WriteLine(dictionary[2]);//"222" //Console.WriteLine(dictionary[4]);//不会像hashtable一样无反应而是直接报错 //2.查看是否存在 // 根据键检测 if (dictionary.ContainsKey(1) ) { Console.WriteLine("存在键为1的键值对"); } // 根据值检测 if (dictionary.ContainsValue("111")) { Console.WriteLine("存在值为111的键值对"); } #endregion #region 改 Console.WriteLine(dictionary[1]); dictionary[1] = "999"; Console.WriteLine(dictionary[1]); #endregion #endregion #region 知识点四 遍历啊 Console.WriteLine("---------------------------"); //长度 Console.WriteLine(dictionary.Count); //1.遍历所有键 Console.WriteLine("---------------------------"); foreach (int item in dictionary.Keys) { Console.WriteLine(item); Console.WriteLine(dictionary[item]); } //2.遍历所有值 Console.WriteLine("---------------------------"); foreach (string item in dictionary.Values) { Console.WriteLine(item); } //3.键值对一起遍历 Console.WriteLine("---------------------------"); foreach (KeyValuePair pair in dictionary) { Console.WriteLine($"键:{pair.Key} 值:{pair.Value}"); } #endregion } } }