11

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", "" });
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • 1
    This will be a lot less awful in the next version of C# which will allow `new Dictionary { ["test"] = "" }`. – Kirk Woll Aug 01 '14 at 23:59

5 Answers5

14

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.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
5

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
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.

AlexD
  • 32,156
  • 3
  • 71
  • 65
2

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.

Chris Walsh
  • 3,423
  • 2
  • 42
  • 62
1

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!

kebin
  • 163
  • 5