【问题标题】:Dictionary .Add not supported C#字典 .Add 不支持的 C#
【发布时间】:2021-06-24 01:43:26
【问题描述】:

我在代码中使用字典如下:

var allValues = new Dictionary<string, int>();
         
while (//condition))
{
    response = // call to a method that returns some values of type Dictionary<string, int> 
    allValues.Add(response);
}  

当我使用 .Add 时,出现以下错误:

我错过了什么?

【问题讨论】:

  • response迭代键值对以添加到allValuesallValues = response;
  • 你不能将字典添加到字典中,你应该从响应中获取键和值并添加
  • 已更新:allValues = response;,此解决方案可能不正确,因为它位于循环内部,并且每次循环迭代都会被覆盖。
  • 您的屏幕截图显示了带有两个预期参数的方法签名。但是您改为传递单个 Dictionary 参数。

标签: c# dictionary


【解决方案1】:

Dictionary 可以作为键/值对的集合进行迭代,因此您可以这样做:

while (condition)
{
    response = // call to a method that returns some values of type Dictionary<string, int> 
    foreach(KeyValuePair<string, int> kvp in response)
    {
        allValues.Add(kvp.Key, kvp.Value);
    }
} 

假设response 本身就是Dictionary

【讨论】:

    【解决方案2】:

    您可以将键值对添加到字典中。试试下面的代码作为例子。

    var allValues = new Dictionary<string, int>();
                int diccounter = 0;
    
                while (true)
                {
                    allValues.Add("a" + diccounter, diccounter++);
                }
    

    【讨论】:

    • @mjwills 是的,我已经举过例子了。
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2022-11-19
    相关资源
    最近更新 更多