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);
}
}
}
Just create a new array in your dictionary
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.