Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 202
sailer Avatar asked Apr 10 '12 13:04

sailer


1 Answers

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); }  list.Add(2); 


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>());  dictionary["foo"].Add(42); dictionary["foo"].AddRange(oneHundredInts); 

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.

like image 184
Adam Houldsworth Avatar answered Sep 19 '22 18:09

Adam Houldsworth