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

本文关键字:列表 字典 嵌套 添加 | 更新日期: 2023-09-27 18:33:44

>我正在尝试创建并填充一个字典,其中包含一个列表作为其值;即

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

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

当我尝试在键下将列表输入字典时会出现此问题。第一个字典赋值很好,例如键"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
}

所以第一个贯穿页面。Movenext(( 循环很好,字典用列表正确填充。但是,在循环的第二次运行时,找到的任何唯一"ValueA"都会添加到列表"ListA"中 - 这会修改已存储在字典中的"ListA"。最终结果是一个字典,其中包含不同的页码作为键,以及每个键的相同庞大的单词列表。

如果我在每个页面循环的开头使用 ListA.Clear(),列表最终会是它阅读的最后一页中的单词,而不是其他内容。

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

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

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

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

你需要:

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

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