Dictionary<>.Add - Inserts at previous Remove index  
Author Message
pvulcan





PostPosted: .NET Base Class Library, Dictionary<>.Add - Inserts at previous Remove index Top

I'm not sure if this is the proper functionality for the Dictionary<>.Add .  Here's the code:

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"item1");
dict.Add(2, "item2");
dict.Add(3, "item3");
dict.Remove(1);
dict.Add(4, "item4");

The dict.Add(4,"item4") adds the item to the beginning of the dictionary object, not the end(which i thought was the intended functionality.  It seems that the Add inserts wherever the Remove index was within the Dictionary.

Is this correct   If so, is there a way to always insert at the end of the Dictionary

Thanks

Paul

 

 



.NET Development4  
 
 
PhilipRieck





PostPosted: .NET Base Class Library, Dictionary<>.Add - Inserts at previous Remove index Top

A Dictionary<> does not represent an ordered list in any way, so the "position" of each element is really meaningless (and an implementation detail). The layout of Dictionary<> is optimized by the implementation to allow for looking up a value for a given key, not iterating over it in a given order.

In fact, the help for the Dictionary<> class states

"For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined."

If you want an ordered list, use the List<> class instead, possibly storing a KeyValuePair in it.