C#等效于python的defaultdict(对于列表)c#[重复]

问题描述 投票:0回答:3

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

但会出现诸如“最佳超载方法匹配的参数无效”之类的错误。

c# python defaultdict
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}); } } }

usage:
Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
dct.AddOrUpdate("key1", "value1");
dct.AddOrUpdate("key1", "value2");

您的第一步应该是用指定的密钥创建记录。然后,您可以在值列表中添加其他值:

0
投票

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

-1
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.