Click here to Skip to main content
15,878,748 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How do I insert an element into a dictionary?
Posted
Comments
phil.o 19-Nov-15 5:50am    
What prevents you from consulting the reference page of the components you are using? :)
Member 11521909 20-Nov-15 21:52pm    
I don't want to add an element, I want to insert an element to a specific index in the dictionary.
phil.o 21-Nov-15 12:21pm    
This is where you are wrong: a dictionary is not meant to sort items in a specific order. That is the functionality of a sorted list.
See my answer for more informations.

It would have been a better World just if they had provided an example...[^].
 
Share this answer
 
Comments
Member 11521909 20-Nov-15 21:52pm    
I don't want to add an element, I want to insert an element to a specific index in the dictionary.
A Dictionary<TKey, TValue> is not meant to sort its items in a specific order. Instead, it uses a key as a quick way (O(n) in Big-O notation) to retrieve a specific item.

Inserting an item at a given position is a list's feature.

Maybe if you describe your issue more precisely we could show you some workarounds.
We would need to know why you need insertion, i.e. the details of your implementation that lead to this requirement.
 
Share this answer
 
This is one of the way to add element in Dictionary,
Dictionary<string,int> dict = new Dictionary<string,int>();
dict.Add("Bat",1);
dict.Add("Ball",2);
dict.Add("Stump",3);

This is one of the way to retrieve element from Dictionary,

foreach(Dictionary<string,int> values in dict)
{
console.WriteLine("Key is {0} and value is {1}", dict.Key,dict.Value);
}
 
Share this answer
 
Comments
Member 11521909 20-Nov-15 21:53pm    
I don't want to add an element, I want to insert an element to a specific index in the dictionary.
Maniraj.M 22-Nov-15 23:28pm    
If you give more importance on index of dictionary you can use indexed dictionary.

IndexedDictionary<string,int> dict = new IndexedDictionary<string,int>();
dict.Add("Ball",1);
dict.Add("Stump",3);
dict.AddAt(1,"Bat",2);
Matt T Heffron 23-Nov-15 13:26pm    
So... If you are using an IndexedDictionary, you should ask where that code came from, it isn't part of the .NET framework.
Assuming it is from the 2009 article here on CodeProject, ask here:
http://www.codeproject.com/Articles/30729/Indexed-Dictionary#_comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900