Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with list of strings as value

I have a dictionary where my value is a List. When I add keys, if the key exists I want to add another string to the value (List)? If the key doesn't exist then I create a new entry with a new list with a value, if the key exists then I jsut add a value to the List value ex.

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>(); myDic.Add(newKey, add to existing list<strings> and not create new one) 
like image 545
user1186050 Avatar asked Jul 26 '13 17:07

user1186050


2 Answers

To do this manually, you'd need something like:

List<string> existing; if (!myDic.TryGetValue(key, out existing)) {     existing = new List<string>();     myDic[key] = existing; } // At this point we know that "existing" refers to the relevant list in the  // dictionary, one way or another. existing.Add(extraValue); 

However, in many cases LINQ can make this trivial using ToLookup. For example, consider a List<Person> which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:

var namesBySurname = people.ToLookup(person => person.Surname,                                      person => person.FirstName); 
like image 154
Jon Skeet Avatar answered Sep 19 '22 05:09

Jon Skeet


I'd wrap the dictionary in another class:

public class MyListDictionary {      private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();      public void Add(string key, string value)     {         if (this.internalDictionary.ContainsKey(key))         {             List<string> list = this.internalDictionary[key];             if (list.Contains(value) == false)             {                 list.Add(value);             }         }         else         {             List<string> list = new List<string>();             list.Add(value);             this.internalDictionary.Add(key, list);         }     }  } 
like image 24
sartoris Avatar answered Sep 23 '22 05:09

sartoris