C# 如何按字母顺序遍历Hashtable的键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/851220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:09:57  来源:igfitidea点击:

How to traverse keys of a Hashtable in alphabetical order?

c#keyhashtabletraversal

提问by Pavel Bastov

What is the easiest way to traverse a hashtable's keys in ascending alphabetical order?

按字母升序遍历哈希表键的最简单方法是什么?

采纳答案by JaredPar

This is fairly dependent upon what the type of the key is. But lets assume for a minute that they are strings. You could use the following LINQ query

这相当依赖于密钥的类型。但是让我们假设它们是字符串。您可以使用以下 LINQ 查询

Hashtable table = GetHashTable();
var keys = table.Keys.Cast<String>().OrderBy(x => x);

For more complex structures the LINQ query is only slightly different. Lets assume you had the following definition for a key

对于更复杂的结构,LINQ 查询只是略有不同。让我们假设您对密钥有以下定义

struct Name {
  public string First;
  public string Last;
  // Equality code omitted
}

The LINQ code would be the following

LINQ 代码如下

Hashtable table = GetHashtable();
var keys = table.Keys.Cast<Name>().OrderBy(x => x.First).ThenBy(x => x.Last);

回答by JH.

Thats not really what hash tables are designed for (they are made to have uniform distribution of keys). Use a sorted tree?

那并不是真正为哈希表设计的(它们被设计为具有均匀的键分布)。使用排序树?

回答by Jon Skeet

If you want a map which keeps its keys in natural order, I suggest you don't use Hashtableto start with. If you're still using 1.1, using System.Collections.SortedList. If you're using 2.0 or higher, use SortedList<TKey, TValue>or SortedDictionary<TKey, TValue>. The latter two are largelythe same in terms of API, but have different performance characteristics - see the docs for more information.

如果您想要一个按自然顺序保存其键的地图,我建议您不要使用Hashtable开始。如果您仍在使用 1.1,请使用System.Collections.SortedList. 如果您使用的是 2.0 或更高版本,请使用SortedList<TKey, TValue>SortedDictionary<TKey, TValue>。后两者在 API 方面基本相同,但具有不同的性能特征 - 有关更多信息,请参阅文档。

回答by Pavel Bastov

Well, I found this snippet to be the most suitable to my situation:

好吧,我发现这个片段最适合我的情况:

Hashtable settings = GetSettings();
ArrayList keys = new ArrayList();
keys.AddRange(settings.Keys);
keys.Sort();
foreach (object key in keys)
{
    // Logic here
}

回答by thecoop

It'll probably be slightly faster to use SortedList -

使用 SortedList 可能会稍微快一点 -

SortedList settings = new SortedList(GetSettings());
foreach (object key in settings.Keys)
{
    //logic
}

creating & sorting the ArrayList is O(n) + O(nlog n) = O(nlog n), whereas the SortedList constructor (according to the docs) is O(n), so it'll be faster to use SortedList directly rather than using an arraylist and explicitly sorting

创建和排序 ArrayList 是 O(n) + O(nlog n) = O(nlog n),而 SortedList 构造函数(根据文档)是 O(n),因此直接使用 SortedList 会更快比使用数组列表并显式排序