C#中的字典操作

Lem*_*mon 0 c# dictionary

我想将以下值存储到字典中:

key(字符串) - 值(字符串列表)

aaa - myfirstvalue1
aaa - myfirstvalue2

bbb - myfirstvalue3

ccc - myfirstvalue4
ccc - myfirstvalue5
Run Code Online (Sandbox Code Playgroud)

字典:

Dictionary<string, List<string> myvalues = new Dictionary<string, List<string>>();
Run Code Online (Sandbox Code Playgroud)

我试图存储这些值,但我得到了重复键错误.

And*_*old 5

字典具有只能添加一次密钥的功能.您拥有正确的类型,但添加数据的方式很重要.

您可以使用以下提供的数据初始化字典:

Dictionary<string, List<string>> myvalues = Dictionary<string, List<string>>
    {
        { "aaa", new List<string> { "myfirstvalue1", "myfirstvalue2" } },
        { "bbb", new List<string> { "myfirstvalue3" } },
        { "ccc", new List<string> { "myfirstvalue4", "myfirstvalue5" } },
    };
Run Code Online (Sandbox Code Playgroud)

有了这个,每个键都有一个分配给它的字符串列表.您可以添加更多这样的值:

 var key = "aaa"; // for example
 if (myvalues.ContainsKey(key)
 {
     myvalues[key].Add("new value");
 }
 else
 {
     myvalues.Add(key, new List<string> { "new value" });
 }
Run Code Online (Sandbox Code Playgroud)

您可以检索以下值:

 List<string> aaaVals = myvalues["aaa"];
Run Code Online (Sandbox Code Playgroud)

然后将其转换List<string>Arraywith List.ToArray().

  • @Lemon不会在[cham​​aleon问题](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions)中对此进行转换.这回答了您原来的问题.如果您有新问题,请提出新问题. (2认同)