【发布时间】: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