为什么在将词典添加到另一个词典时,我得到“无需重载的方法为1参数”?

时间:2016-11-11 07:28:33

标签: c# dictionary

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

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

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

我收到以下错误:

  

方法“添加”没有重载需要1个参数

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

解决!

我一直在使用如下的扩展方法,它运行OK ^^

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

1 个答案:

答案 0 :(得分:1)

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

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

mapStudentData.Add("strKey", dicValue);

mapStudentData["strKey"] = dicValue;

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