2012-02-16 112 views
1

我如何在c#中的關鍵基礎上對散列表進行排序。例如:

例如:按關鍵字排序Hashtable?

Hastable hst = new Hashtable(); 
hst.Add("Key1","keyValue"); 
hst.Add("Key2","keyValue"); 
hst.Add("Key3","keyValue"); 
+3

*排序*的概念幾乎沒有任何意義的散列表。 – 2012-02-16 08:11:07

+0

需要什麼? – 2012-02-16 08:11:36

+0

可能重複[c#哈希表按鍵排序](http://stackoverflow.com/questions/9280054/c-sharp-hashtable-sorted-bykeys) – GSerg 2016-08-09 06:59:03

回答

3

如果需要排序的強類型的散列表,你可以使用SortedDictionary<TKey, TValue>

var hst = new SortedDictionary<string, string>(); 
hst.Add("Key1","keyValue"); 
hst.Add("Key2","keyValue"); 
hst.Add("Key3","keyValue"); 

如果你想堅持一個哈希表:

IEnumerable<DictionaryEntry> sortedEntries = hst.OrderBy(entry => entry.Key); 
1

看看這個問題,答案有很大的。 Is it possible to sort a HashTable?

哈希表通過將鍵映射到值來工作。隱含在這個映射中的概念是密鑰不按任何特定順序排序或存儲。 但是,你可以看看SortedDictionary<K,V>.

另一種選擇是按照你已經做的構造哈希表,然後從關鍵字構造一個有序集合。您可以遍歷該排序的鍵集,根據需要從哈希表中獲取相應的值。