简体   繁体   中英

Iterating through C# dictionary with KeyValuePair

I try to iterate through dictionary , but it shows me this error :

"cannot convert from 'System.Collections.Generic.KeyValuePair' to 'string'".

Can you tell me how to solve this problem?

Here's the code:

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

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

Thank you in advance.

You cannot assign a type KeyValuePair to a string instead you can extract the key and value like this:

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

Following should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM