Why do I get "No overload method for Add takes one argument" when adding a Dictionary to the list of dictionaries

Sorry if this is basic. I'm a little new to C #, but why can't I add a dictionary to the list of dictionaries? The documentation I was looking through is as follows:

List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); data.Add(new Dictionary<string, string>() { "test", "" }); 
+6
source share
5 answers

When you create your Dictionary<string, string> in the second line, you do not initialize it correctly.

What you need:

 List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); data.Add(new Dictionary<string, string>() { {"test", ""} }); 

This creates a new key / value pair and adds it to the dictionary. The compiler, although you tried to add an element called "test" and one called "" in the dictionary; which you cannot do, because add operations require a value as well as a key.

+11
source

You are using a collection initializer for a list or array. The dictionary has keys and values, so it must have a set of parameters in curly brackets:

 data.Add( new Dictionary<string, string>() { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } } ); 

Initialize the dictionary using the collection initializer

+5
source

Add additional {}

 data.Add(new Dictionary<string, string>() { {"test", ""} }); 

Without additional brackets, you are trying to add two separate lines, "test" and "" , while you want to add a key-value pair.

+3
source

OK The list of dictionaries is likely to complicate the issue too much. You get the same error only with this line:

 var x = new Dictionary<string, string>() { "test", "" }; 

The problem is filling out the dictionary this way. If my example has been changed to:

 var x = new Dictionary<string, string>(); x.Add("test", ""); 

and then back to the original example, this will work:

  List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); var x = new Dictionary<string, string>(); x.Add("test", "" ); data.Add(x); 

By the way, why do you need a list of dictionaries. Sounds like a pretty compiled design pattern to use - albeit technically sound.

+2
source

The dictionary object expects a key and a value, while you pass only the key. When initializing the dictionary, you need to do the following:

 var anObject = new Dictionary<string, string>{ {"key", "value"} }; 

If you initialize anObject with several elements, it will be:

 var anObject = new Dictionary<string, string> { { "key1", "val1" }, { "key2", "val2" } }; 

Hope this helps!

+1
source

Source: https://habr.com/ru/post/973245/


All Articles