【问题标题】:Adding lists to a nested list dictionary将列表添加到嵌套列表字典
【发布时间】:2013-10-04 05:27:19
【问题描述】:

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

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
}

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

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

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

【问题讨论】:

    标签: c# list dictionary


    【解决方案1】:

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

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

    你需要:

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

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

    【讨论】:

    • 这正是我所需要的,非常感谢!为什么我以前没看到?!啊!
    • @Eomo Classic 问题。不要心情不好。当您将变量添加到另一个对象时,可能很难判断变量是通过值传递还是通过引用传递。
    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多