c#Hashtable按键排序

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

ExchangeA, 200 ExchangeV, 100 ExchangeC, 200 

就像这样

 ExchangeA, 200 ExchangeC, 200 ExchangeV, 100 

您可以使用SortedDictionary来为您进行按键排序。 在你的情况下, SortedDictionary可以工作:

 SortedDictionary dict = new SortedDictionary(); 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); } 

输出:

 Key = Exchange A, Value = 200 Key = Exchange C, Value = 200 Key = Exchange V, Value = 100 

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

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

但是,我没有订购原始哈希表,只是按顺序读取它的值。

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

由于哈希表的性质,您无法对密钥进行排序:它们根据哈希代码(哈希表控件之外的值)在桶中组织密钥。 但是,您可以按照您喜欢的顺序读取键值对。 以下是使用LINQ的方法:

 IDictionary d = ...; // your hash table var ordered = d.OrderBy(p => p.Key).ToList(); foreach (var p in ordered) { Console.WriteLine("Key: {0} Value: {1}", p.Key, p.Value); } 

使用Linq很简单( using System.Linq ):

 var sortedList = (from kv in MyDictionary select kv order by kv.Key).ToList>(); 

返回KeyValuePair

使用列表而不是哈希(或将哈希值转换为字典),并执行以下操作:

 var dictionary = new Dictionary(); var l = dictionary.Keys.ToList(); l.Sort(); foreach (var key in l) { Console.WriteLine(dictionary[key]); } 

我使用一个列表来存储Hashtable的键并对其进行排序,然后使用这个排序列表来显示Hashtable。 这是我的代码:

  List lst = new List(); foreach (var key2 in ht.Keys) { lst.Add(key2.ToString()); } lst.Sort(); foreach (var item in lst) { Console.WriteLine(string.Format("{0},{1}", item, ht[item.ToString()])); }