将列表添加到嵌套列表字典中

时间:2013-10-03 21:06:21

标签: c# list dictionary

我正在尝试创建并填充包含列表的字典作为其值;即

Dictionary <string, List<string>> DictionaryA = new Dictionary<string,List<string>>();

然后将字典中的值输出到Excel电子表格中。

当我尝试在Key下的Dictionary中输入列表时出现问题。第一个字典分配很好,例如Key“Key1”下的10个字符串列表。

Dictionary <string, List<string>> DictionaryA = new Dictionary<string, List<string>>();
int i = 0;
while(page.MoveNext()) //For example, for each page in a book
{
  while(words.MoveNext()) //For example, words in the page
  {
    if(!(ListA.Contains(ValueA)) //For example, we are looking to store instances of each word in each page of a book
    {
       ListA.Add(ValueA);
    }
    DictionaryA.Add(i, ListA);
    i++;
  }

  sortedList = DictionaryA.Keys.ToList(); //Let's say we want to sort the Dictionary as well
  sortedList.Sort()

  foreach (var key in sortedList)
  {
    DictionaryASorted.Add(key, DictionaryA[key]);
  }

  ExcelOuput(DictionaryASorted); //Function to export and save an Excel File
}

所以第一次运行page.Movenext()循环没问题,字典正确地填充了列表。但是,在第二次循环运行时,找到的任何唯一“ValueA”都会添加到列表“ListA”中 - 这会修改已存储在Dictionary中的“ListA”。最终结果是一个包含不同页码作为键的字典,以及每个键的相同巨大的单词列表。

如果我在每个页面循环的开头使用ListA.Clear(),那么List最终会成为它读取的最后一页的单词。

如何在不更改以前修改的列表的情况下使用此嵌套列表?我想以正确的方式做到这一点吗?或者是否有更好,更优雅的解决方案?

1 个答案:

答案 0 :(得分:0)

您需要在循环中创建一个新列表。

所以,就在while(words.MoveNext())

之上

你需要:

List<string> ListA = new List<string>();

这将创建一个新列表供您填充。你必须意识到字典和ListA都指向同一个列表。添加或清除列表对字典引用的列表执行相同操作。您需要为每个字典值创建一个新列表。