Setting value in jagged dictionary sets all values
I have a jagged dictionary:
Dictionary<string, Dictionary<int, Dictionary<string, string>>> tierOptions = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();
Later on, I have code that sets one of those values in the array:
tierOptions[optionID][npID]["tName"] = cboTier.Text;
The problem is that when it runs through this portion of code, all "tName" elements are set to cboTier.Text instead of just the one element.
For instance if optionID was 1 and npID was 8, and I had these three:
tierOptions[1][8]["tName"]
tierOptions[2][8]["tName"]
tierOpti开发者_Go百科ons[3][8]["tName"]
That particular line of code would set all three, instead of just tierOptions[1][8]["tName"]
Any idea why it is doing this? Thanks!
It sounds simply like you have used the same dictionary instance in several "dimensions" (your terminology). Since this is a reference, they are all shared (there is no automatic clone-into-isolated-copies here).
When filling the data, take care to use isolated dictionary instances when the data should be separate.
Yep, I would say the sae as Marc. Please take a look at this example how you can retreive the vlaue from your type of Dictionary:
Dictionary<string, Dictionary<int, Dictionary<string, string>>> dic = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();
//add to 1st dic:
dic.Add("A", new Dictionary<int, Dictionary<string, string>>());
//add to 2nd dic:
dic["A"].Add(1, new Dictionary<string, string>());
//add to 3rd dic:
dic["A"][1].Add("a", "value 1");
//string KeyIn3rdDic = dic["A"][1].ToString();
string ValueIn3rdDic = dic["A"][1]["a"]; //result is "value 1";
精彩评论