【发布时间】:2012-04-23 17:02:23
【问题描述】:
我有一个Dictionary<string, IEnumerable<string>> 类型的字典和一个字符串值列表。出于某种原因,每次我执行 Add 时,字典中的每个值都会被覆盖。我完全不知道为什么会这样。我确保在循环中声明和初始化 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 是我的字典。
【问题讨论】:
-
你已经“关闭了循环变量”。您添加的每个
lst都将使用 lasttype变量。请阅读:blogs.msdn.com/b/ericlippert/archive/2009/11/12/… 有趣的是,这个问题将在 C#5 中消失! -
我一定会阅读的。再次感谢大家的帮助!
标签: c# linq dictionary