C# nested dictionaries
c#, dictionary, nested
Solution
You cannot define a class field using `var`.
Change `var` to `Dictionary<string, Dictionary<string, string>>`:
public Dictionary<string, Dictionary<string, string>> info =
new Dictionary<string, Dictionary<string, string>>
{
{
"Gen",
new Dictionary<string, string>
{
{"name", "Genesis"},
{"chapters", "50"},
{"before", ""},
{"after", "Exod"}
}
},
{
"Exod",
new Dictionary<string, string>
{
{"name", "Exodus"},
{"chapters", "40"},
{"before", "Gen"},
{"after", "Lev"}
}
}
};
See here for more information about `var` keyword and its usage.
In C# 9, with the introduction of target-typed new expressions, you can rewrite the field definition as:
public Dictionary<string, Dictionary<string, string>> info = new()
{
{
"Gen",
new Dictionary<string, string>
{
{"name", "Genesis"},
{"chapters", "50"},
{"before", ""},
{"after", "Exod"}
}
},
{
"Exod",
new Dictionary<string, string>
{
{"name", "Exodus"},
{"chapters", "40"},
{"before", "Gen"},
{"after", "Lev"}
}
}
};
Problem
What is wrong with my syntax? I want to be able to get the value "Genesis" with this `info["Gen"]["name"]` ``` public var info = new Dictionary<string, Dictionary<string, string>> { {"Gen", new Dictionary<string, string> { {"name", "Genesis"}, {"chapters", "50"}, {"before", ""}, {"after", "Exod"} }}, {"Exod", new Dictionary<string, string> { {"name", "Exodus"}, {"chapters", "40"}, {"before", "Gen"}, {"after", "Lev"} }}}; ```