简体   繁体   中英

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"}
    }}};

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.

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>>{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM