Abhi_Dev
Abhi_Dev

Reputation: 99

Sorting Hashtable on key Basis?

How do i sort hashtable on key basis in c#.

Eg.

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

Upvotes: 1

Views: 4635

Answers (2)

Dor Cohen
Dor Cohen

Reputation: 17080

Look at this question, the answer there are great. Is it possible to sort a HashTable?

Hashtables work by mapping keys to values. Implicit in this mapping is the concept that the keys aren't sorted or stored in any particular order. However, you could take a look at SortedDictionary<K,V>.

Another option is to construct the hash table as you're already doing, and then simply construct a sorted set from the keys. You can iterate through that sorted key set, fetching the corresponding value from the hash table as needed.

Upvotes: 1

vc 74
vc 74

Reputation: 38179

If you need a sorted strongly typed hashtable, you can use SortedDictionary<TKey, TValue>

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

If you want to stick to a hashtable:

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

Upvotes: 3

Related Questions