tags:

views:

52

answers:

3

For Dictionary<,> "The order in which the items are returned is undefined".

I know there is SortedDictionary, but if I just want a dictionary that gives me back the elements in the order I put them in, what is the best thing to do?

I'm thinking that I should use a List<KeyValuePair<,>> and convert that to a Dictionary when I need to do a lookup (as opposed to doing a foreach on the Dictionary).

Or am I missing something smarter?

A: 

If you're using .NET 4.0 you probably may to try

SortedList<Tuple<T1,T2>>

where Tuple replaces KeyValuePair

or as @BenW said:

Queue<Tuple<T1,T2>>
abatishchev
Surely using a Queue<T> (FIFO) would be better in that case
BenW
SortedList (and SortedDictionary) both sort using a `IComparer` this is not the same as "insertion order".
Daniel Renshaw
Seems to me that SortedList would end up being ordered by whatever the default comparer for `Tuple<T1,T2>` is?
Benjol
+4  A: 

There is a non-generic class that does this: OrderedDictionary but currenty there is no generic version.

Daniel Renshaw
Thanks, that's something I didn't know about.
Benjol
+1  A: 

Derive from dictionary and create a backing list that you synchronize with the dictionary. Whenever items are added/removed you add/remove them to the list (same with Clear()).

This would allow you to implement other custom sorting as well.

erash