Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I iterate through a Dictionary (.NET generic data structure) will it be in the same order that I added them?

I have a dictionary that I normally access with a key, so I need fast random access reads. However for one function I need to process every item in the dictionary where the order is important. It seems to be working OK in tests. Is it OK to depend on the order of items in a dictionary?

like image 901
tpower Avatar asked Nov 03 '08 09:11

tpower


1 Answers

No. If you need to keep an order, you should have a list of items as well. You could encapsulate all the operations you need in your own collection class, which would update both the dictionary and the list at the same time.

It's unfortunate that .NET doesn't have a dictionary which supports this itself - it's a reasonably common request - Java does, as LinkedHashMap.

like image 145
Jon Skeet Avatar answered Sep 27 '22 21:09

Jon Skeet