C#中利用Dictionary进行基于键值的元素快速查找 | 您所在的位置:网站首页 › 字典模糊查询 › C#中利用Dictionary进行基于键值的元素快速查找 |
它的样式是Dictionary Class,TKey表示字典中键的类型,TValue表示字典中值的类型,任何键都必须是唯一的。 以下是关于官方示例的引用 static void Main(string[] args) { Dictionary openWith = new Dictionary(); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is // already in the dictionary. try { openWith.Add("txt", "winword.exe"); } catch (ArgumentException) { Console.WriteLine("An element with Key = \"txt\" already exists."); } Console.WriteLine("For key = \"rtf\", value = {0}.",openWith["rtf"]); if (!openWith.ContainsKey("ht"))//验证键值是否存在 { openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } // 仅仅得到值的集合 Dictionary.ValueCollection valueColl = openWith.Values; Console.WriteLine(); foreach (string s in valueColl) { Console.WriteLine("Value = {0}", s); } //仅仅得到键的集合 Dictionary.KeyCollection keyColl = openWith.Keys; Console.WriteLine(); foreach (string s in keyColl) { Console.WriteLine("Key = {0}", s); } }利用这个方法来解决字符串中某个字符出现的次数特别简单 class Program { static Dictionary dic = new Dictionary(); static void Main(string[] args) { int i = 6; while(i>0) { Insert(Console.ReadLine()); i--; } foreach (var item in dic) { if (item.Value == 1) { Console.WriteLine("第{0}值出现了一次", item.Key); } } } public static void Insert(string c) { if (dic.ContainsKey(c))//ContainsKey包含则为真 dic[c]++; else dic[c] = 1; } } |
CopyRight 2018-2019 实验室设备网 版权所有 |