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");
但会出现诸如“最佳超载方法匹配的参数无效”之类的错误。
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");
您的第一步应该是用指定的密钥创建记录。然后,您可以在值列表中添加其他值:
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
List<string> mList;
if (!dct.TryGetValue("key1", out mList))
{
mList = new List<string>();
dct.Add("key1", mList);
}
mList.Add("value1");
mList.Add("value2");