http://bytes.com/topic/c-sharp/answers/962687-foreach-cannot-convert-type
Varkin writes:
So I have a button that calls a Class. The Method reads a file, stores the results in a Dictionary (tried Hashtable first and got the same error). I return the Dictionary variable. Then I try to loop through the results so I can save and reuse them later. For testing I am just trying to put the results into a listbox.
I'm getting the error: CS0030 Cannot convert type 'char' to 'System.Collections.Generic.KeyValuePair<string, string>'
I'm getting the error: CS0030 Cannot convert type 'char' to 'System.Collections.Generic.KeyValuePair<string, string>'
class getCharacter
{
public string getCharNow()
{
string fldr = "c:\\temp\\character.txt";
fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fldr;
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(fldr);
Dictionary<string, string> charProfile = new Dictionary<string, string>();
do
{
string getLine = objReader.ReadLine();
int findSplit = getLine.IndexOf(":");
string heading = getLine.Substring(0, findSplit);
string headingValue = getLine.Substring(findSplit + 1);
charProfile.Add(heading.ToString(), headingValue.ToString());
} while (objReader.Peek() != -1);
objReader.Close();
return charProfile.ToString();
}
}
private void getChar_Click(object sender, EventArgs e)
{
getCharacter getProfile;
getProfile = new getCharacter();
string profile = getProfile.getCharNow();
foreach (KeyValuePair<string, string> pair in profile)
{
listBox1.Items.Add(pair.Key + " : " + pair.Value);
}
}
The solution requires returning Dictionary <string, string> not a string from getCharacter.getCharacter function.
{
public Dictionary<string, string> getCharNow()
{
string fldr = "c:\\temp\\character.txt";
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(fldr);
Dictionary<string, string> charProfile = new Dictionary<string, string>();
do
{
string getLine = objReader.ReadLine();
int findSplit = getLine.IndexOf(":");
string heading = getLine.Substring(0, findSplit);
string headingValue = getLine.Substring(findSplit + 1);
charProfile.Add(heading.ToString(), headingValue.ToString());
} while (objReader.Peek() != -1);
objReader.Close();
return charProfile;
}
}
private void button1_Click(object sender, EventArgs e)
{
getCharacter getProfile;
getProfile = new getCharacter();
Dictionary<string,string> profile = getProfile.getCharNow();
foreach (KeyValuePair<string,string> pair in profile)
{
listBox1.Items.Add(pair.Key + " : " + pair.Value);
}
}