c# dictionary How to add multiple values for single key?

I have created dictionary object

Dictionary<string, List<string>> dictionary =
    new Dictionary<string,List<string>>();

I want to add string values to the list of string for a given single key. If the key doesn’t already exists then I have to add a new key. List<string> is not predefined, I mean I didn’t create any list object and then supplied to dictionary.Add("key",Listname). How to create dynamically this list object in dictionary.Add("key",Listname) and then add strings to this list. If I have to add 100 keys then do I have to create 100 lists before executing dictionary.Add instruction and also do I have to pedefine the contents of this lists ?

Thank you.


Update: check for existence using TryGetValue to do only one lookup in the case where you have the list:

List<int> list;

if (!dictionary.TryGetValue("foo", out list))
    list = new List<int>();
    dictionary.Add("foo", list);


Original: Check for existence and add once, then key into the dictionary to get the list and add to the list as normal:
var dictionary = new Dictionary<string, List<int>>();

if (!dictionary.ContainsKey("foo"))
    dictionary.Add("foo", new List<int>());


Or List<string> as in your case.

As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>, favour the constructor that takes the initial list capacity: new List<int>(100);.

This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.

Leave a Reply

Your email address will not be published. Required fields are marked *