Dictionary( TKey , TValue )算法
表示键和值的集合。code
Dictionary( TKey, TValue) 泛型类提供了从一组键到一组值的映射。字典中的每一个添加项都由一个值及其相关联的键组成。经过键来检索值的速度是很是快的,接近于 O(1),这是由于Dictionary( TKey, TValue) 类是做为一个哈希表来实现的。(检索速度取决于为 TKey 指定的类型的哈希算法的质量。)对象
只要对象用做 Dictionary( TKey, TValue) 中的键,它就不能以任何影响其哈希值的方式更改。使用字典的相等比较器比较时,Dictionary( TKey, TValue) 中的任何键都必须是惟一的。键不能为 null 。 可是若是值类型 TValue 为引用类型,该值则能够为空。string
经常使用方法it
using System; using System.Collections.Generic; public class Example { public static void Main() { //1、建立泛型哈希表,而后加入元素 Dictionary<string, string> oscar = new Dictionary<string, string>(); oscar.Add("哈莉?贝瑞", "《死囚之舞》"); oscar.Add("朱迪?丹奇", "《携手人生》"); oscar.Add("尼科尔?基德曼", "《红磨坊》"); oscar.Add("詹妮弗?康纳利", "《美丽心灵》"); oscar.Add("蕾妮?齐维格", "《BJ单身日记》"); //2、删除元素 oscar.Remove("詹妮弗?康纳利"); //3、假如不存在元素则加入元素 if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不伦之恋》"); //4、显然容量和元素个数 Console.WriteLine("元素个数: {0}", oscar.Count); //5、遍历集合 Console.WriteLine("74届奥斯卡最佳女主角及其电影:"); foreach (KeyValuePair<string, string> kvp in oscar) { Console.WriteLine("姓名:{0},电影:{1}", kvp.Key, kvp.Value); } //6、获得哈希表中键的集合 Dictionary<string, string>.KeyCollection keyColl = oscar.Keys; //遍历键的集合 Console.WriteLine("最佳女主角:"); foreach (string s in keyColl) { Console.WriteLine(s); } //7、获得哈希表值的集合 Dictionary<string, string>.ValueCollection valueColl = oscar.Values; //遍历值的集合 Console.WriteLine("最佳女主角电影:"); foreach (string s in valueColl) { Console.WriteLine(s); } //8、使用TryGetValue方法获取指定键对应的值 string slove = string.Empty; if (oscar.TryGetValue("朱迪?丹奇", out slove)) Console.WriteLine("我最喜欢朱迪?丹奇的电影{0}", slove); else Console.WriteLine("没找到朱迪?丹奇的电影"); //9、清空哈希表 oscar.Clear(); Console.ReadLine(); } }