【问题标题】:C# equivalent of Python's defaultdict (for lists) in C# [duplicate]C# 中 Python 的 defaultdict(用于列表)的等价物 [重复]
【发布时间】:2014-01-28 15:38:20
【问题描述】:

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

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

【问题讨论】:

  • 给出错误的原因是您没有为字典值传递List&lt;string&gt;
  • 当它应该是 List&lt;string&gt; 时,您正在添加 string 作为值
  • dct.Add("key1", new List&lt;string&gt;().Add("value1"));

标签: c# python defaultdict


【解决方案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】:

    您的第一步应该是使用指定键创建记录。然后你可以在值列表中添加额外的值:

    Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>();
    dct.Add("key1", new List<string>{"value1"});
    dct["key1"].Add("value2");
    

    【讨论】:

    • 有什么方法可以获取 Python 版本提供的默认值?这似乎需要不同的代码,具体取决于密钥是否已经存在。
    • @user2357112,开箱即用 - 没有。不过,您始终可以为此实施扩展
    【解决方案3】:
    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);
    

    【讨论】:

    • 有什么方法可以获取 Python 版本提供的默认值?这似乎需要不同的代码,具体取决于密钥是否已经存在。
    • 不行,你得自己写代码。
    猜你喜欢
    • 2013-10-08
    • 2013-11-14
    • 2013-06-21
    • 2017-10-14
    • 2012-08-27
    • 1970-01-01
    • 2013-11-04
    • 2012-02-01
    • 2011-12-15
    相关资源
    最近更新 更多