0

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");

但这会产生诸如“最佳重载方法匹配具有无效参数”之类的错误。

4

3 回答 3

2

这是您可以添加到项目中以模拟您想要的行为的扩展方法:

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");
于 2014-01-28T16:11:39.043 回答
1

您的第一步应该是使用指定键创建记录。然后您可以将其他值添加到值列表中:

Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.Add("key1", new List<string>{"value1"});
dct["key1"].Add("value2");
于 2014-01-28T15:40:58.550 回答
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);
于 2014-01-28T15:42:14.617 回答