简体   繁体   中英

Unsort or unorder HashTable in .net

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM