[英]Dictionary with list of strings as value
我有一个字典,我的值是List。 当我添加密钥时,如果密钥存在,我想在值(List)中添加另一个字符串? 如果密钥不存在,那么我创建一个带有值的新列表的新条目,如果密钥存在,那么我将jsut添加到List值ex的值。
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, add to existing list<strings> and not create new one)
要手动执行此操作,您需要以下内容:
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);
但是,在许多情况下,LINQ可以使用ToLookup
来实现这一点。 例如,考虑一个List<Person>
,它要转换为“surname”字典到“姓氏的名字”。 你可以使用:
var namesBySurname = people.ToLookup(person => person.Surname,
person => person.FirstName);
我将字典包装在另一个类中:
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);
}
}
}
只需在字典中创建一个新数组
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.