为什么Dictionary.Add会覆盖我字典中的所有项目?

Ann*_*ath 6 c# linq dictionary

我有一个类型字典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);
}
Run Code Online (Sandbox Code Playgroud)

在哪里typelist是一个IEnumerable<string>,root是一个XElement,serialLists是我的词典.

Mar*_*ell 10

这是捕获的迭代器问题.

尝试:

foreach (string tmp in typelist)
{
   string type = tmp;
Run Code Online (Sandbox Code Playgroud)

(其余不变)

或者,我会在添加期间评估表达式,即在.Add中执行.ToList():

    serialLists.Add(type, lst.ToList());
Run Code Online (Sandbox Code Playgroud)

第二种选择可能总体上更有效,尽管它确实强制评估可能永远不需要的thigs.


Dou*_*las 6

原因是,你的IEnumerable<string>序列不被急切地填充,但点播,之后foreach循环会完成所有的迭代.因此,当IEnumerable<string>枚举任何序列时,type变量将始终具有最后一个元素的值typelist.

这是一个简单的方法来解决它:

foreach (string type in typelist)
{
    string typeCaptured = type;

    IEnumerable<string> lst = 
        from row in root.Descendants()
        where row.Attribute("serial").Value.Substring(0, 3).Equals(typeCaptured)
        select row.Attribute("serial").Value.Substring(3).ToLower();

    serialLists.Add(typeCaptured, lst);
}
Run Code Online (Sandbox Code Playgroud)