如何使用数组值初始化字典?

时间:2016-07-18 09:04:13

标签: c# arrays dictionary

我有以下代码:

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

哪个不对。错误列表包含以下内容:

  

方法无过载&#39;添加&#39;需要3个参数

     

没有任何论据符合所需的形式参数&#39;值&#39; &#39; Dictionary.Add(string,string [])&#39;

我基本上只想用预设值初始化我的词典。不幸的是,我不能使用代码方式初始化,因为我在静态类中工作,其中只有变量。

我已经尝试过这些东西了:

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

但我没有运气。任何帮助表示赞赏。

PS:如果我使用两个参数,则日志显示为can't convert from string to string[]

5 个答案:

答案 0 :(得分:4)

这适用于我(围绕另一组{} - 为您创建的KeyValuePair),因此它无法找到您尝试执行的功能:

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

我建议遵循C#{}惯例 - 良好的缩进有助于轻松找到这些问题:)

答案 1 :(得分:2)

您必须在{}中围绕每个键值对,您可以new[]{...}使用string[]

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

答案 2 :(得分:1)

字典中的每个条目都应该用{}括起来,并且键值对应该用,

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

如果您正在使用C#6,则可以利用新语法:

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

答案 3 :(得分:0)

对于数组初始化,无效。对于匿名类型来说,这是一次失败的尝试:

string[] array = new { "a", "b" }; // doesn't compile

你也错过了一些大括号:

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

或者:

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

答案 4 :(得分:0)

试试这个:

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