Dictonary.Keys.

  • Thread starter Thread starter Mr. X.
  • Start date Start date
M

Mr. X.

I have Declared
Dictionary<string, string> myDict;

I want to search all the keys values.
What's wrong of the following :

string keyStr;
string valueStr;
....
for (i = 0; i <= myDict.Count - 1; i++)
{
keyStr = (string)(myDict.Keys); // ***** this doesn't
compile ! what should I write instead *******
valueStr = myDict[keyStr];
}

Thanks :)
 
I have Declared
Dictionary<string, string> myDict;

I want to search all the keys values.
What's wrong of the following :

string keyStr;
string valueStr;
...
for (i = 0; i <= myDict.Count - 1; i++)
{
keyStr = (string)(myDict.Keys); // ***** this doesn't
compile ! what should I write instead *******
valueStr = myDict[keyStr];
}


The answer to your specific question is below:

foreach (string key in myDict.Keys)
{
string value = myDict[key];
}

However, this is not necessarily the best way to iterate a dictionary. You
can get both the key and the value at the same time by using a
KeyValuePair<K, V> object:

foreach (KeyValuePair<string, string> kvp in myDict)
{
// Now you can access kvp.Key and kvp.Value
}
 
Back
Top