-1

Sorry if this is basic. Why cant I add a Dictionary to a another Dictionary? Given the following code:

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

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

I get the following errors:

No overload for method 'Add' takes 1 arguments

Any tips on these will be great help. Thanks in advance.


Solved!

I have been using extension methods like below, it run 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);
}

And use like this:

mapStudentData["strKey"].AddRange(dicValue);
MinhKiyo
  • 191
  • 3
  • 15
  • 1
    Asked and answered http://stackoverflow.com/questions/3982448/adding-a-dictionary-to-another – CollinD Nov 11 '16 at 07:30
  • 2
    `mapStudentData.Add("strKey", dicValue);` – Dmitry Bychenko Nov 11 '16 at 07:30
  • if doing so, add the same Key will throw Exception – MinhKiyo Nov 11 '16 at 07:34
  • Thank you for the help. Because of duplicate question, so I will review the available information as link that CollinD had instructions – MinhKiyo Nov 11 '16 at 07:35
  • This is not a duplicate of that question. That question asks how to add all pairs in a simple (e.g. `string`/`string`) dictionary into another one. This question seems to be about adding a dictionary to a dictionary of dictionaries. – Rawling Nov 11 '16 at 08:57
  • 2
    Or `mapStudentData["strKey"] = dicValue;` It is pretty weird seeing attempt at mixing the two aproaches. – Euphoric Nov 11 '16 at 08:59
  • Thank everybody for the help. Based on the link above, I did it run ok. – MinhKiyo Nov 11 '16 at 09:03
  • @MinhKiyo I'm glad your issue is fixed. I've added an answer that explains why your initial code had problems, and the two ways to fix it (and how they are different). – Lars Kristensen Nov 11 '16 at 09:21
  • Ok, I've updated to add the solution to the question. – MinhKiyo Nov 11 '16 at 10:19

1 Answers1

1

By referencing mapStudentData["strKey"] you request the Value from the KeyValuePair of mapStudentData Dictionary. So when you afterwards try to call the Add method, you are doing it on the Dictionary which requires two arguments; a Key (in your case, a string) and a Value (in your case, a Dictionary).

To fix your issue, you need to change the last line to either:

mapStudentData.Add("strKey", dicValue);

or

mapStudentData["strKey"] = dicValue;

The first one will add a completely new entry in the dicitionary and throw an exception if an entry with the same key already exists. The second one will "add or overwrite" without throwing an exception if the key already exists.

Lars Kristensen
  • 1,410
  • 19
  • 29