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)
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);
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With