2

I am trying to declare a dictionary whose values are string arrays. How can I do this?

I tried the following code (which does not work):

Dictionary<string, string[]> NewDic = new Dictionary<string,string[]>
{
    {"Key_0", {"Value_0.0", "Value_0.1"}},
    {"Key_1", {"Value_1.0", "Value_1.1", "Value_1.2"}},
}
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Gaduks
  • 671
  • 6
  • 13

1 Answers1

9

You need to specify that your values are arrays like:

using implicitly typed array

 {"Key_0", new[] {"Value_0.0", "Value_0.1"}},

Or explicitly specifying the type

 {"Key_0", new string[] {"Value_0.0", "Value_0.1"}},

So your class could look like:

public static class NewClass
{
    private static Dictionary<string, string[]> NewDic = new Dictionary<string, string[]>
    {
        {"Key_0", new[] {"Value_0.0", "Value_0.1"}},
        {"Key_1", new string[] {"Value_1.0", "Value_1.1", "Value_1.2"}},
    };
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    @Gaduks, you are welcome, *Although*, not directly related but you can also use [indexed members](https://msdn.microsoft.com/en-us/magazine/dn683793.aspx) with C# 6.0 like `["Key_0"] = new[] { "Value_0.0", "Value_0.1" },` – Habib Apr 01 '15 at 16:07