我想按键值的升序循环遍历哈希表,我设置的int值在1-20之间。
原始代码:
IDictionaryEnumerator crcEnumerator = crcHashTable.GetEnumerator();
while(crcEnumerator.MoveNext())
{
// does stuff with the keys/values
}
它在哈希表中循环,但顺序相反(20比1,而不是升序)。
我尝试使用
foreach(DictionaryEntry de in crcHashTable)
但是它仍然以相反的顺序循环通过哈希表。
如何根据哈希表的键值按升序循环?
谢谢你的帮助!
您使用了错误的数据结构。改为使用SortedDictionary
:
Hashtable hash = new Hashtable();
hash[3] = "three";
hash[1] = "one";
hash[2] = "two";
var dictionary = hash.Cast<DictionaryEntry>().ToDictionary(kvp => (int)kvp.Key, kvp => (string)kvp.Value);
var sorted = new SortedDictionary<int, string>(dictionary);
只需确保包括:
using System.Collections;
using System.Collections.Generic;
using System.Linq;