I have following code using class and dictionary that takes state and capital, but I'm unable to retrieve the values by looping through. Need assistance is clearing up the error that occurs in foreach loop.
public class State {
public string Capital { get; set; }
public int Population { get; set; }
public int Size { get; set; }
public State(string aCapital, int aPopulation, int aSize) {
Capital = aCapital;
Population = aPopulation;
Size = aSize;
} // Constructor of the class State
public static Dictionary<string, State> GetStates() {
Dictionary<string, State> myStates = new Dictionary<string, State>(); // need the () because its a class
// myStates takes 2 values, one is a string , that is a state and State , which is inturn takes 3 values -
// Capital,Population, size
State addStateCapital = new State("Montgomery", 214141, 244);
myStates.Add("Alabama", addStateCapital);
// second set
addStateCapital = new State("Sacramento", 214141, 244);
myStates.Add("California", addStateCapital);
return myStates;
}
}
and my Main program is as follows.. But I get error..
var theState= State.GetStates();
// this prints one item in a dictionary
Console.WriteLine("State Capital of California is " + theState["California"].Capital);
foreach (KeyValuePair<string,object> entry in theState)
{
Console.WriteLine(entry.Key + " State Capital is " + entry.Value.ToString());
}
ERROR on foreach:
Cannot convert keyvaluePair <string,DictionaryDemo.State> to System... Generic KVP<string,object>
Need help in understanding how to correctly retrieve the values.
KeyValuePair<string, State>to aKeyValuePair<string, object>. I suggest just usingforeach (var entry in theState).