Alex Rivera | Logout

How to insert element in first index in dictionary?

Asked 2012-01-06T16:33:13.107
23

Is there a method or technique that allows you to insert an element into a Dictionary<TKey, TValue> guaranteeing that the item is in the first index of that dictionary's KeyCollection.

For example:

Dictionary<String, String> dic = foo.GetOutput(); 

// `dic` is something like:

// {"foo", "baa"},
// {"a", "b"}

I need something like:

dic.Add("key", "value", 0);
// where `0` is the index that `key` to be inserted.

foreach(KeyValuePair<String, String> key in dic) 
{
     Console.WriteLine("{0} = {1}", key.Key, key.Value);
}

Output:

key = value
foo = baa
a = b
Edit
Report

1 Answer

2

The Dictionary<TKey,TValue> class does not hold items in an ordered manner, so there is no "first" item.

There is a SortedDictionary<Tkey,TValue> (.NET 4.0+), which sorts by the key, but again, this is a very vague idea of "first".

answered 2012-01-06T16:35:07.013

Your Answer