问题
What is the easiest way to traverse a hashtable's keys in ascending alphabetical order?
回答1:
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
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
struct Name {
public string First;
public string Last;
// Equality code omitted
}
The LINQ code would be the following
Hashtable table = GetHashtable();
var keys = table.Keys.Cast<Name>().OrderBy(x => x.First).ThenBy(x => x.Last);
回答2:
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 }
回答3:
If you want a map which keeps its keys in natural order, I suggest you don't use Hashtable
to 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 largely the same in terms of API, but have different performance characteristics - see the docs for more information.
回答4:
Thats not really what hash tables are designed for (they are made to have uniform distribution of keys). Use a sorted tree?
回答5:
It'll probably be slightly faster to use 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
来源:https://stackoverflow.com/questions/851220/how-to-traverse-keys-of-a-hashtable-in-alphabetical-order