Why am i getting “No overload method for Add takes 1 argument” when adding a Dictionary to a List of Dictionaries

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

Sorry if this is basic. I am a little new to C#, but why cant I add a Dictionary to the list of Dictionaries? The documentation I have looked up does it like this:

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

回答1:

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

What you need is this:

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 though you were trying to add an element called "test" and one called "" to the dictionary; which you can't do because those add operations require a value as well as a key.



回答2:

You are using the collection initializer for a list or array. A dictionary has keys and values, so it needs to have a set of parameters in braces:

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

Initialize a Dictionary with a Collection Initializer



回答3:

Add extra {}

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

Without extra brackets, you are trying to add two individual strings, "test" and "", while you want to add a key-value pair.



回答4:

OK. The "List of Dictionaries" is probably over complicating the issue. You get the same error just with this line:

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

The issue is populating a dictionary in this manner. If my example was changed to:

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

then going back to your 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); 

BTW, why would you require a list of dictionaries. Sounds quite a compilcated design pattern to use - although technically valid.



回答5:

The dictionary object is expecting key and value, while you are only passing the key. When initializing a dictionary you need to do the following:

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

If initializing anObject with multiple items then it would be:

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

Hope that helps!



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!