Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# nested dictionaries

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"}
    }}};
like image 861
user1898657 Avatar asked Mar 19 '13 13:03

user1898657


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.


2 Answers

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.

like image 199
Mohammad Dehghan Avatar answered Sep 20 '22 06:09

Mohammad Dehghan


From MSDN;

  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

  • var cannot be used on fields at class scope.

  • Variables declared by using var cannot be used in the initialization expression.

Just change your var to Dictionary<string, Dictionary<string, string>>. Like;

public Dictionary<string, Dictionary<string, string>> info =
    new Dictionary<string, Dictionary<string, string>>{}
like image 27
Soner Gönül Avatar answered Sep 18 '22 06:09

Soner Gönül