sinsedrix
sinsedrix

Reputation: 4775

How to insert a key/value pair into a dictionary?

When I add an entry to a Dictionary using Add, the KeyValuePair is added at the end of it. I would like to preppend it thus when I iterate on KeyValuePair's, it is the first item.

Is there a way to do it with a Dictionary or should I build a List<KeyValuePair<TKey, TValue>> or do you have a better proposition?

EDIT : I thought I could work on the enumeration in Dictionary, it seems I can't.

I tried with List<KeyValuePair<TKey, TValue>> which was not very practical.

Upvotes: 2

Views: 1740

Answers (5)

Oded
Oded

Reputation: 498904

The Dictionary class doesn't have a concept of order within it - there is no positional index to the Dictionary.

Take a look at the OrderedDictionary class in the System.Collections.Specialized namespace if you need to use a positional index on a dictionary.

Upvotes: 12

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

Officially, you can never know in what order your key-value pairs will come out of a Dictionary<,> if you iterate through it (foreach it, thereby calling GetEnumerator()). And certainly, if you Remove some items from your dictionary, and later Add some other items, when you foreach your way through the collection, the new items will be in the space of the removed items, not in the end of the iteration "list".

But: If you know you never Delete from your Dictionary<,>, it looks like the enumeration yields the items in the order they were added. There is no guarantee this will always work, but it looks like it works in the current implementation.

So if you dare rely on this, you could just say

foreach (var keyValuePair in myDict.Reverse())
{
  ...

The Reverse method is part of LINQ (needs using System.Linq).

Upvotes: 0

NominSim
NominSim

Reputation: 8511

If you are looking to preserve order, Dictionary is not the collection that you want to use (it doesn't have a concept of order).

There is an OrderedDictionary collection that will help if you need to have an indexed dictionary.

There is also a SortedDictionary collection, that will sort the values that you add based on the key value.

Upvotes: 3

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20745

Use OrderedDictionary.

Represents a collection of key/value pairs that are accessible by the key or index. You can insert the key value pait at desired index.

Upvotes: 3

Tim S.
Tim S.

Reputation: 56536

I think you're looking for the OrderedDictionary.

Upvotes: 4

Related Questions