Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an dictionary with an array value?

I have the following code:

public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>() {
    "key1", { "value", "another value", "and another" }
};

Which is incorrect. The Error List contains the following:

No overload for method 'Add' takes 3 arguments

There is no argument given that corresponds to the required formal parameter 'value' of 'Dictionary.Add(string, string[])'

I basically just want to initialize my Dictionary with preset values. Unfortunately, I can't use code-wise initialization, because I'm working in a static class, which only has variables in it.

I have already tried these things:

  • ... {"key1", new string[] {"value", "another value", "and another"}};
  • ... {"key", (string[]) {"value", "another value", "and another"}};

But I had no luck. Any help is appreciated.

PS: If I use two parameters, the log says can't convert from string to string[].

like image 522
ForceMagic Avatar asked Dec 10 '22 15:12

ForceMagic


1 Answers

This works for me (surrounding with another set of {} - for the KeyValuePair that you create) so it doesn't find the function you are trying to execute:

Dictionary<string, string[]> dict = new Dictionary<string, string[]>
{
    { "key1", new [] { "value", "another value", "and another" } },
    { "key2", new [] { "value2", "another value", "and another" } }
};

I'd suggest to follow C# {} conventions - good indentation helps to find these problems easily :)

like image 106
Gilad Green Avatar answered Jan 01 '23 11:01

Gilad Green