Hashtable的优化查找,每次增加元素时先计算hash 并把key放到hash对应的桶中去。 然后,查找元素时先计算出hashcode 并到对应的桶中去遍历key ,速度很快。老版本.NET Framework 中的类型它是比一般的 Dictionary 类型慢。
using System.Collections; class Program { static Hashtable GetHashtable() { // Create and return new Hashtable. Hashtable hashtable = new Hashtable(); hashtable.Add("Area", 1000); hashtable.Add("Perimeter", 55); hashtable.Add("Mortgage", 540); return hashtable; } public static void Main() { Hashtable hashtable = GetHashtable(); // See if the Hashtable contains this key. Console.WriteLine(hashtable.ContainsKey("Perimeter")); // Test the Contains method. It works the same way. Console.WriteLine(hashtable.Contains("Area")); // Get value of Area with indexer. int value = (int)hashtable["Area"]; // Write the value of Area. Console.WriteLine(value); } }
True True 1000
字典最关键的是快速查找。Dictionary提供了快速查找键并获取值。它的键和值可以使用的任何类型,包括整数和字符串。
词典需要一种特殊的语法形式。
使用有许多不同类型的元素的词典时,最好指定其键类型和值类型。这能提高性能。.
class Dict { static void Main() { // Example Dictionary again Dictionary<string, int> d = new Dictionary<string, int>() { {"Lion", 2}, {"dog", 1}}; // Loop over pairs with foreach foreach (KeyValuePair<string, int> pair in d) { Console.WriteLine ("{0}, {1}",pair.Key, pair.Value); } foreach (var pair in d) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } Console.ReadKey(); } }
2KB项目(www.2kb.com,源码交易平台),提供担保交易、源码交易、虚拟商品、在家创业、在线创业、任务交易、网站设计、软件设计、网络兼职、站长交易、域名交易、链接买卖、网站交易、广告买卖、站长培训、建站美工等服务