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)
小智 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