【问题标题】:c# Iterate through hashtable in reverse orderc#逆序遍历hashtable
【发布时间】:2016-07-09 21:47:44
【问题描述】:

我想按键值的升序遍历哈希表,我设置在 1-20 之间。

原码:

IDictionaryEnumerator crcEnumerator = crcHashTable.GetEnumerator();

while(crcEnumerator.MoveNext()) 
{ 
   // does stuff with the keys/values 
}

它循环遍历哈希表,但顺序相反(20 到 1,而不是升序)。

我试图尝试使用

foreach(DictionaryEntry de in crcHashTable) 

但它仍然以相反的顺序循环遍历哈希表。

如何根据哈希表的键值升序遍历?

感谢您的帮助!

【问题讨论】:

  • 有什么理由使用已经过时 10 年的 Hashtable?
  • 如果您确实需要对集合和排序问题进行迭代,请尝试使用 SortedDictionary 和 IEnumerable 的 .Reverse 方法
  • 尝试使用for loop 而不是使用++ 增量使用-- 有很多关于如何在反向循环中循环Collection 的示例。你可以使用这些示例作为首发..
  • 这个问题毫无意义。基于哈希的集合没有顺序!

标签: c# sorting dictionary hashtable enumerator


【解决方案1】:

您使用了错误的数据结构。请改用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2011-05-18
    相关资源
    最近更新 更多