我有一个 Dictionary<string, IEnumerable<string>>
类型的字典和字符串值列表。出于某种原因,每次我执行添加时,字典中的每个值都会被覆盖。我完全不知道为什么会这样。我确保在循环内声明和初始化 IEnumberable 对象不是引用问题,这样它的范围就不会超出一次迭代,而且它仍然会这样做。这是我的代码:
foreach (string type in typelist)
{
IEnumerable<string> lst =
from row in root.Descendants()
where row.Attribute("serial").Value.Substring(0, 3).Equals(type)
select row.Attribute("serial").Value.Substring(3).ToLower();
serialLists.Add(type, lst);
}
哪里typelist
是一个 IEnumerable<string>
, root
是一个 XElement
, 和 serialLists
是我的词典。
最佳答案
这是一个捕获的迭代器问题。
尝试:
foreach (string tmp in typelist)
{
string type = tmp;
(其余不变)
或者,我会在添加期间评估表达式,即在 .Add 中执行 .ToList():
serialLists.Add(type, lst.ToList());
第二个选项可能总体上更有效,尽管它确实强制对可能永远不需要的事物进行评估。
关于c# - 为什么 Dictionary.Add 会覆盖我字典中的所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284926/