使用 KeyValuePair 遍历 C# 字典

tra*_*ata 1 c# string iteration foreach dictionary

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

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

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

这是代码:

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

               .............     
}
Run Code Online (Sandbox Code Playgroud)

先感谢您。

Ous*_* D. 5

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

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