C#相当于做什么:
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> dct['key1'].append('value1')
>>> dct['key1'].append('value2')
>>> dct
defaultdict(<type 'list'>, {'key1': ['value1', 'value2']})
现在,我有:
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.Add("key1", "value1");
dct.Add("key1", "value2");
但是会出现“最佳重载方法匹配包含无效参数”之类的错误。
答案 0 :(得分:1)
您的第一步应该是使用指定的密钥创建记录。然后,您可以向值列表中添加其他值:
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.Add("key1", new List<string>{"value1"});
dct["key1"].Add("value2");
答案 1 :(得分:1)
以下是您可以添加到项目中的扩展方法,以模拟您想要的行为:
public static class Extensions
{
public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, List<TValue>> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
dictionary[key].Add(value);
}
else
{
dictionary.Add(key, new List<TValue>{value});
}
}
}
用法:
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.AddOrUpdate("key1", "value1");
dct.AddOrUpdate("key1", "value2");
答案 2 :(得分:0)
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
List<string>() mList = new List<string>();
mList.Add("value1");
mList.Add("value2");
dct.Add("key1", mList);