简体   繁体   English

字典与字符串列表作为值

[英]Dictionary with list of strings as value

I have a dictionary where my value is a List. 我有一个字典,我的值是List。 When I add keys, if the key exists I want to add another string to the value (List)? 当我添加密钥时,如果密钥存在,我想在值(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. 如果密钥不存在,那么我创建一个带有值的新列表的新条目,如果密钥存在,那么我将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)

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 . 但是,在许多情况下,LINQ可以使用ToLookup来实现这一点。 For example, consider a List<Person> which you want to transform into a dictionary of "surname" to "first names for that surname". 例如,考虑一个List<Person> ,它要转换为“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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM