C#中哈希表(HashTable)用法实例详解(添加/移除/判断/遍历/排序等

2019-12-30 13:14:03王冬梅

4. 遍历哈希表

遍历哈希表需要用到DictionaryEntry Object,代码如下:


for(DictionaryEntry de in ht) //ht为一个Hashtable实例
{
  Console.WriteLine(de.Key); //de.Key对应于keyvalue键值对key
  Console.WriteLine(de.Value); //de.Key对应于keyvalue键值对value
}

遍历键


foreach (int key in hashtable.Keys)
{
  Console.WriteLine(key);
}

遍历值


foreach (string value in hashtable.Values)
{
  Console.WriteLine(value);
}

5. 对哈希表进行排序

对哈希表按key值重新排列的做法:


ArrayList akeys=new ArrayList(ht.Keys);
akeys.Sort(); //按字母顺序进行排序
foreach(string key in akeys)
{
  Console.WriteLine(key + ": " + ht[key]); //排序后输出
}

6. 哈希表的效率

System.Collections下的哈希表(Hashtable)和System.Collections.Generic下的字典(Dictionary)都可用作lookup table,下面比较一下二者的执行效率。


Stopwatch sw = new Stopwatch();
Hashtable hashtable = new Hashtable();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
int countNum = 1000000;
sw.Start();
for (int i = 0; i < countNum; i++)
{
  hashtable.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); //输出: 744
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  dictionary.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); //输出: 489
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  hashtable.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); //输出: 245
sw.Restart();
for (int i = 0; i < countNum; i++)
{
  dictionary.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); //输出: 192

由此可见,添加数据时Hashtable快。频繁调用数据时Dictionary快。

结论:Dictionary<K,V>是泛型的,当K或V是值类型时,其速度远远超过Hashtable。

希望本文所述对大家C#程序设计有所帮助。

 

注:相关教程知识阅读请移步到c#教程频道。