tags:

views:

1492

answers:

3

hi

ive decided to learn c# recently. ive done some php before. i see c# has dictionaries. thats equivalent to an associative array in php right? as far as i can tell the dictionary doesnt maintain insertion order like php associative arrays right? is there some other equivalent i should use if insertion order is important?

thanks

+3  A: 

Dictionary doesn't guarantee to preserve insertion order, so no: you can't rely on that (although it is hard to force it to break this). If insertion order is important, you would need to create a hybrid class, perhaps encapsulating a List<T> for the inserted order, and a Dictionary<TKey,T> for the indexing.

Marc Gravell
Java has one (LinkedHashMap). There's really no equivalent in C#?
cletus
@cletus: No. there's really no equivalent in the core .NET framework. @Marc: It's not that hard to force it. I can't remember it offhand, admittedly... it's in a post somewhere, I think.
Jon Skeet
if you tend to get ordering with a hashtable it implies your hash function is crap and your O(1) is at risk. you should have close to random insertion position for any bucket...
ShuggyCoUk
+2  A: 

You might want to check out Power Collections. I believe they have implementations that would suit your needs.

HTH, Kent

Kent Boogaart
A: 

There is an OrderedDictionary class in the System.Collections.Specialized namespace, but it's unfortunately not generic.

There is no built-in, generic dictionary class that preserves insertion order. If insertion order is really important, you'll have to roll your own or check out a third party implementation (as Marc & Kent suggested).

John Price