Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert element in first index in dictionary?

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
like image 377
Jack Avatar asked Jan 06 '12 16:01

Jack


3 Answers

By not using a dictionary.

Dictionary<TKey, TValue> is implemented as a hash-table. The position of keys internal to the dictionary depends upon the hash-code, the means by which that hash-code was reduced further to provide an index into its internal structure, and the order of insertion in an entirely implementation-dependant way.

This isn't the only way to implement a dictionary. SortedDictionary<TKey, TValue> uses a tree structure internally and so always keeps keys in an order. In this case we still can't insert something in the beginning, rather we insert something and it gets put in the appropriate place.

If ordering is what you care about most, then you don't want a puredictionary at all. Rather you want either a List<KeyValuePair<TKey, TValue>> or you want a structure that offers both the functionality of a list and of a dictionary, which is provided by OrderedDictionary. This isn't generic, but you can easily create a generic wrapper around it (doesn't give the performance benefits of internally using generics, but does give type-safety in use).

like image 177
Jon Hanna Avatar answered Nov 20 '22 22:11

Jon Hanna


I know it is a three years old question. But found a workaround of this problem. It may help someone

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

dic = (new Dictionary<string, string> {{"key","value"}}).Concat(dic).ToDictionary(k => k.Key, v => v.Value);

This will insert the element in the beginning of dictionary :)

like image 25
MJK Avatar answered Nov 20 '22 23:11

MJK


Dictionaries are unordered; elements are meant to be retrieved with a key, whose hash points to its value's location.

What you might want is a List <KeyValuePair>, whose elements can be inserted into a specific index.

List<KeyValuePair<string, string>> list = dic.ToList();
list.Insert(0, new KeyValuePair<string, string>("a", "b"));

foreach(KeyValuePair<string, string> pair in list)
    Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
like image 9
Adam Rackis Avatar answered Nov 20 '22 21:11

Adam Rackis