3

I guess everything is in the title...

I know that Dictionary<TKey,TValue> does keep the keys in addition order, but only as long as you don't remove any, and anyway this behavior is not documented and can't be relied upon (see this question for details).

Basically, what collection should I use if I want an ordered collection of key/value pairs, while keeping an O(1) access time? (List<KeyValuePair<K,V>> isn't a good option since it would have O(n) access time). I don't think there is anything like that in the BCL, but I just want to be sure before I roll my own...

Just to make it clear to everyone: I don't want the keys to be sorted, I just want them to remain in addition order. So SortedList/SortedDictionary are not what I'm looking for...

Community
  • 1
  • 1
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758

5 Answers5

2

If you can accept non-generic, then System.Collections.Specialized.OrderedDictionary may do what you need. Otherwise, I would be tempted to write a wrapper that combines a list and dictionary, using the list for GetEnumerator and the dictionary for the indexer.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

Could you perhaps just keep a List and a Dictionary that allows you to lookup where keys are in the list? That would allow you to get the key/value pairs in order of addition but still maintain O(1) lookup.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
1

So, you don't want an associative container and the order is completely based on insertion order... why don't you simply use a basic array?

Brandon Moretz
  • 7,512
  • 3
  • 33
  • 43
1

"Addition order" is not normally an issue for a Dictionary, so don't expect one int a std library.

It is of course possible but will always come at the cost of performance. If you find O(1) lookup important I would suggest a wrapper containing a Dictionary<K,V> and an coupled List<K>. Add and Remove will become slower.

H H
  • 263,252
  • 30
  • 330
  • 514
0

You could use a SortedDictionary with a custom IComparer that maintains the insertion order. Whether you want to wrap this in your own more convenient interface is up to you, of course.

Domenic
  • 110,262
  • 41
  • 219
  • 271
  • Thanks, but I don't see how the IComparer would know about the insertion order... Did you have an implementation in mind? – Thomas Levesque Nov 07 '11 at 21:55
  • Since you implement the `IComparer` yourself, and you know the insertion order, you certainly could make one that knows the insertion order. Again, might need some wrapping to be user-friendly. – Domenic Nov 07 '11 at 22:03