Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 580
trakiiskasalata Avatar asked May 08 '26 10:05

trakiiskasalata


2 Answers

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;    
       ...
       ...          
} 
like image 117
Ousmane D. Avatar answered May 10 '26 16:05

Ousmane D.


Following should work

foreach (var keyValue in dict)
{
       var key = keyValue.Key;
       var value = keyValue.Value;    
       //other logic
} 
like image 25
SSD Avatar answered May 10 '26 14:05

SSD