c#Hashtable按键排序

Joh*_*ann 6 c# sorting hashtable jquery-ui-sortable

我有一个哈希表,其中键是字母键,值是数字键.如何根据键对哈希表进行排序?

ExchangeA, 200
ExchangeV, 100
ExchangeC, 200
Run Code Online (Sandbox Code Playgroud)

就像这样

ExchangeA, 200
ExchangeC, 200
ExchangeV, 100
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 13

您可以使用a SortedDictionary来为您执行按键排序.在你的情况下,一个 SortedDictionary<string, int>会工作:

SortedDictionary<string, int> dict = new SortedDictionary<string, int>();
dict.Add("Exchange C", 200);
dict.Add("Exchange A", 200);
dict.Add("Exchange V", 100);

foreach (var kvp in dict)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Key = Exchange A, Value = 200
Key = Exchange C, Value = 200
Key = Exchange V, Value = 100
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,SortedDictionary 是由二叉搜索树内部实现的,并且具有 O(lg n) 检索而不是哈希表的预期 O(1) 检索。根据 OP 的需要,他可能想要这个,或者他可能想要像其他答案一样执行 OrderBy (2认同)
  • @GabeMoothart还有另一个优点:`SortedDictionary <,>`:它不使用数组,而`Dictionary <,>`.如果你有大量的对象而且你遇到了大对象堆碎片的问题,`SortedDictionary <,>`是一个快速的解决方案,可以让你的数据远离大对象堆. (2认同)

小智 5

我发现"排序"哈希表的最简单方法是:

var hash = new Hashtable();
var orderedKeys = hash.Keys.Cast<string>().OrderBy(c => c); // supposing you're using string keys
var allKvp = from x in orderedKeys select new{ key = x, value = hash[x] };
Run Code Online (Sandbox Code Playgroud)

但是,我没有订购原始哈希表,只是以有序的方式读取它的值.

与其他回复一样,如果您需要以排序方式存储您的数据,最好是使用SortedDictionary