Reputation: 195
I have problem with put values into Dictionary.
My Code:
Dictionary<string, Dictionary<string, int>> cnDict = new Dictionary<string, Dictionary<string, int>>();
Dictionary<string, int> cn = new Dictionary<string,int>();
cn.Add("DynamicPanel_1", 0);
cn.Add("DynamicPanel_3", 1);
cn.Add("DynamicPanel_4", 0);
this.cnDict.Add("DynamicPanel_2", cn);
cn.Clear();
cn.Add("DynamicPanel2", 1);
cn.Add("DynamicPanel3", 0);
this.cnDict.Add("DynamicPanel1", cn);
foreach(KeyValuePair<string, int> pos in cnDict["DynamicPanel_2"])
{
MessageBox.Show("DynamicPanel_2 has values: "+ pos.Key + " ----> " + pos.Value.ToString()); ;
}
foreach (KeyValuePair<string, int> pos in cnDict["DynamicPanel_1"])
{
MessageBox.Show("DynamicPanel_1 has values: " + pos.Key + " ----> " + pos.Value.ToString()); ;
}
This code display wrong messages:
DynsmicPanel_2 has values: DynamicPanel_3 ----> 0
DynsmicPanel_1 has values: DynamicPanel_2 ----> 1
Should be:
DynsmicPanel_2 has values: DynamicPanel_4 ----> 0
DynsmicPanel_1 has values: DynamicPanel_2 ----> 1
What I do wrong ?
Thanks
Upvotes: 1
Views: 66
Reputation: 12807
You add same cn
object twice to cnDict
dictionary. Create new object: replace cn.Clear();
by cn = new Dictionary<string,int>();
Upvotes: 3