【问题标题】:Iterating through C# dictionary with KeyValuePair使用 KeyValuePair 遍历 C# 字典
【发布时间】:2018-08-12 06:02:48
【问题描述】:

我尝试遍历 dictionary,但它显示了这个错误

“无法从 'System.Collections.Generic.KeyValuePair' 转换为 'string'”。

你能告诉我如何解决这个问题吗?

代码如下:

var dict = new SortedDictionary<string, string>();
foreach(KeyValuePair<string, string> ugh in dict){

               .............     
}

提前谢谢你。

【问题讨论】:

  • 显示完整代码。显示的代码不应导致您所说的错误。

标签: c# string dictionary foreach iteration


【解决方案1】:

您不能将类型 KeyValuePair 分配给 string,而是可以像这样提取键和值:

var dict = new SortedDictionary<string, string>();
foreach (KeyValuePair<string, string> keyValue in dict)
{
       var key = keyValue.Key;
       var value = keyValue.Value;    
       ...
       ...          
} 

【讨论】:

    【解决方案2】:

    以下应该可以工作

    foreach (var keyValue in dict)
    {
           var key = keyValue.Key;
           var value = keyValue.Value;    
           //other logic
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-24
      • 2019-09-12
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多