0

I am working with the hashtable in C# and due to some reason I don't get the expected result as the Hashtable sorts all the entries.

I wanna remove this sorting as I already have list in a particular ordered that needs to be printed

The list gets added to hashtable correctly based on the order but when I iterate through the HashTable, it sorts all the entries and produces completely sorted entries. BTW I am using DictionaryEntry for iterating through the hashtable.

Thanks

Aneesh
  • 187
  • 1
  • 3
  • 18

1 Answers1

3

This is the expected behaviour. It is not sorting the entries, Hashtables entries are iterated in a non-determinstic order. They are optimised for random access and as a consequence insertion order is not preserved in the HashTable structure, and so the entries cannot be iterated in insertion order.

According to the MSDN page serialising and deserializing the hashtable can cause the iteration order to be changed.

You might be able to use the NameValueCollection or SortedDictionary as outlined in this question/answer

Your other option (assuming that neither of the options above do what you want) is to create a class which does exactly what you want. You could track entries and store them in a list (as well as the hashtable), then return the iterator for the list rather than the hashtable from your class so you could get both iteration in order and fast random access.

Community
  • 1
  • 1
Sam Holder
  • 32,535
  • 13
  • 101
  • 181
  • Thanks for that. But the problem is I have a list associated with every key in the hashtable. Basically I used Hashtable for this reason so that I can hold a collection of strings based on the hashtable key. So first I iterate through HashTable values picks its LIst and iterate through the list – Aneesh Oct 13 '11 at 09:44
  • Why can't you use SortedDictionary> then? (or what ever type the elements in your list are? – Sam Holder Oct 13 '11 at 09:58
  • what do you mean it sorts the list alphabetically. It would help to have a sample of the code which does not work. – Sam Holder Oct 14 '11 at 07:12