4

Possible Duplicate:
C# associative array

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

Community
  • 1
  • 1

4 Answers4

4

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Java has one (LinkedHashMap). There's really no equivalent in C#? – cletus Feb 23 '09 at 12:45
  • @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 Feb 23 '09 at 13:51
  • 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 Feb 24 '09 at 00:53
2

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

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
1

PHP associative arrays are converted to type XmlRpcStruct. See the XML-RPC spec.

In C#, use XmlRpcStruct or struct to represent PHP associative arrays.

This is a tested solution, not an offhand suggestion.

Dan Hermes
  • 11
  • 1
1

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).

AwesomeTown
  • 2,800
  • 2
  • 27
  • 41