Dictonary.Keys.

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 :)
 
J

Jeff Johnson

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
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top