嵌套字典值为空,C#

时间:2016-06-16 01:19:20

标签: c# dictionary

我对以下表格有回复:

page1Title:507
page1URL:577

我的代码应该将页面的每个属性映射到嵌套字典中的页面键,并为所有页面执行此操作:

 Dictionary<string,string> mapOfSinglePage = new Dictionary<string, string>();
 Dictionary<string,Dictionary<string,string>> mapOfAllPages = new Dictionary<string, Dictionary<string, string>>();
string[] keys = { "title", "url","description","owner","cat", "pts" };
            for (int i = 1; i < 11; i++)
            {
                foreach (string key in keys) {
                    mapOfSinglePage[key] = Regex.Split(responses[i], "<br />")[Array.IndexOf(keys, key)].Split(':')[1];
                }
                mapOfAllPages[i + ". page"] = mapOfSinglePage;
                mapOfSinglePage.Clear();
            }
            String response = "";
            string help = "";
            foreach (KeyValuePair<string, Dictionary<string, string>> kvp in mapOfAllPages)
            {
                foreach(KeyValuePair<string,string> kvp2 in kvp.Value)
                {
                    help+= string.Format("Key : {0}, Value : {1}", kvp2.Key, kvp2.Value);
                }
                response+= string.Format("Key : {0}, Value : {1}", kvp.Key, help);
                help = "";
            }
                Response.Write(response);

问题是,当我打印出来时,它出现了

Key : 1. page, Value : Key : 2. page, Value : Key : 3. page 

等等。换句话说,mapOfSllPage字典在被映射到mapOfAllPages时是空的

如果mapOfSinglePage字典的clear()在分配给mapOfAllPages之前,似乎是正常的行为,但事实并非如此。

还是我打错了?对我来说似乎并非如此

1 个答案:

答案 0 :(得分:0)

你的问题是:

  mapOfAllPages[i + ". page"] = mapOfSinglePage;
  mapOfSinglePage.Clear();

您假设这会复制mapOfSinglePage并将该副本放入mapOfAllPages[i + ". page"],然后清除原始Dictionary

没有。它使mapOfAllPages[i + ". page"]指向mapOfSinglePage ,然后将其清除

您每次都需要创建一个新的Dictionary,并且永远不要清除它。

相关问题