C# 以字符串列表作为值的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17887407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dictionary with list of strings as value
提问by user1186050
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.
我有一本字典,其中我的值是一个列表。当我添加键时,如果键存在,我想向值(列表)添加另一个字符串?如果键不存在,那么我创建一个带有值的新列表的新条目,如果键存在,那么我将向列表值 ex 添加一个值。
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, add to existing list<strings> and not create new one)
回答by Jon Skeet
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:
但是,在许多情况下,LINQ 可以使用ToLookup
. 例如,考虑一个List<Person>
您想将其转换为“姓氏”到“该姓氏的名字”的字典。你可以使用:
var namesBySurname = people.ToLookup(person => person.Surname,
person => person.FirstName);
回答by sartoris
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);
}
}
}
回答by Victor Hugo martinence
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));