【问题标题】:Why am i getting “No overload method for Add takes 1 argument”when adding a Dictionary to a another Dictionary?为什么在将字典添加到另一个字典时出现“Add 的重载方法需要 1 个参数”?
【发布时间】:2017-03-25 09:33:37
【问题描述】:

对不起,如果这是基本的。为什么我不能将字典添加到另一个字典?给定以下代码:

var mapStudentData = new Dictionary<string, Dictionary<int, List<Student>>>();

var dicValue = new Dictionary<int, List<Student>>();
mapStudentData["strKey"].Add(dicValue);

我收到以下错误:

方法 'Add' 没有重载需要 1 个参数

任何关于这些的提示都会有很大帮助。提前致谢。


解决了!

我一直在使用下面的扩展方法,运行正常^^

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException("target");
    if(source==null)
      throw new ArgumentNullException("source");
    foreach(var element in source)
        target.Add(element);
}

并像这样使用:

mapStudentData["strKey"].AddRange(dicValue);

【问题讨论】:

  • mapStudentData.Add("strKey", dicValue);
  • 如果这样做,添加相同的Key会抛出异常
  • 感谢您的帮助。由于重复的问题,所以我将查看可用信息作为 CollinD 有说明的链接
  • 或mapStudentData["strKey"] = dicValue; 看到混合这两种方法的尝试非常奇怪。

标签: c# dictionary


【解决方案1】:

通过引用mapStudentData["strKey"],您从mapStudentData Dictionary 的KeyValuePair 请求值。因此,当您之后尝试调用 Add 方法时,您是在需要两个参数的 Dictionary 上执行此操作;一个键(在您的情况下为string)和一个值(在您的情况下为Dictionary)。

要解决您的问题,您需要将最后一行更改为:

mapStudentData.Add("strKey", dicValue);

或

mapStudentData["strKey"] = dicValue;

第一个将在字典中添加一个全新的条目,如果已​​经存在具有相同键的条目,则抛出异常。如果密钥已经存在,第二个将“添加或覆盖”而不抛出异常。

【讨论】:

  • 感谢您的帮助!我已更新以添加问题的解决方案。
  • @MinhKiyo 很高兴它可以提供帮助。您可以将答案标记为“已接受”,以便其他人知道您找到了问题的解决方案。
猜你喜欢
  • 1970-01-01
  • 2018-07-27
  • 2013-10-08
  • 2011-04-28
  • 1970-01-01
  • 2018-07-07
  • 2022-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多