使用KeyValuePair

时间:2018-03-04 13:30:42

标签: c# string dictionary foreach iteration

我尝试遍历词典,但它显示了错误

  

"无法转换为' System.Collections.Generic.KeyValuePair'到'字符串'"。

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

以下是代码:

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

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

提前谢谢。

2 个答案:

答案 0 :(得分:1)

您无法将类型KeyValuePair分配给string,而是可以像这样提取密钥和值:

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

答案 1 :(得分:0)

以下应该工作

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