Search code examples
c#object-initializers

How to construct an instance of Dictionary<string, List<string>>


I am trying to code in C#, but I find that I can't construct an instance in this way like C++:

Dictionary<string, List<string>> FirSet =
    new Dictionary<string, List<string>>() {
        { "a", {"ab", "abc"} },
        { "b", {"bc", "bcd"} }
    };

Solution

  •     var firSet =
            new Dictionary<string, List<string>>()
            {
                { "a", new List<string>() {"ab", "abc"} },
                { "b", new List<string>() {"bc", "bcd"} }
            };
    

    You can also use the C# 6.0 syntax:

        var firSet =
            new Dictionary<string, List<string>>()
            {
                ["a"] = new List<string> {"ab", "abc"},
                ["b"] = new List<string> {"bc", "bcd"}
            };
    

    And if you feel particularly lazy and you don't want to type all these new List<string> you can always do this:

        var firSet =
            new Dictionary<string, string[]>()
            {
                { "a", new[] {"ab", "abc"} },
                { "b", new[] {"bc", "bcd"} }
            }
            .ToDictionary(i => i.Key, i => i.Value.ToList());