1

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"} }
    };
6
  • 6
    You need new List<string>() before your list items. So { "a", {"ab", "abc"} } should become { "a", new List<string>() {"ab", "abc"} } Commented Apr 16, 2018 at 14:54
  • 1
    Do you really need a List<string> or can it be a string[] array? You can use that initialization syntax with arrays. For lists, you need to new one up for each dictionary value. Commented Apr 16, 2018 at 14:54
  • 1
    @itsme86 wouldnt you still need to new up an array in that case? new [] { "some", "example" }? Commented Apr 16, 2018 at 14:55
  • 1
    You're also missing a closing } Commented Apr 16, 2018 at 14:55
  • @maccettura Oops, you're right. Commented Apr 16, 2018 at 14:59

2 Answers 2

6

You have to initiate the lists within the dictionary with new List<string>()

Here how it should work:

Dictionary<string, List<string>> FirSet = new Dictionary<string, List<string>>()
{
    { "a", new List<string> { "ab", "abc" }},
    { "b", new List<string> { "bc", "bcd" }}
};
Sign up to request clarification or add additional context in comments.

4 Comments

Minor point, but if you're going to drop the () (which I prefer) from the latter list creation, you should also do it for the first one.
Since our answers are (now) the same, I've deleted mine and upvoted yours.
@DavidG yes you are completaly right, its unnecessary, but since its possible i wanted to show both ways. might help FreAk Apoint in the future
@ZoharPeled thank you, to be fair i just threw the answer out, dmigo was so kind to format it like it is
2
    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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.