Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IEnumerable在更改时减少';什么内容?_C#_Linq To Xml_Ienumerable - Fatal编程技术网

C# IEnumerable在更改时减少';什么内容?

C# IEnumerable在更改时减少';什么内容?,c#,linq-to-xml,ienumerable,C#,Linq To Xml,Ienumerable,我发现了许多奇怪的行为。当我使用Linq to XML创建一个集合,然后循环该集合并更改其元素时,每次通过循环时,集合大小都会减少1。以下是我所说的: var nodesToChange = from A in root.Descendants() where A.Name.LocalName == "Compile" && A.Attribute("Include").

我发现了许多奇怪的行为。当我使用Linq to XML创建一个集合,然后循环该集合并更改其元素时,每次通过循环时,集合大小都会减少1。以下是我所说的:

    var nodesToChange =  from A in root.Descendants()
                         where A.Name.LocalName == "Compile"
                         && A.Attribute("Include").Value.ToLower().Contains(".designer.cs")
                         && A.HasElements && A.Elements().Count() == 1
                         select A;
    foreach (var node in nodesToChange) {
          //after this line the collection is reduced
          node.Attribute("Include").Value = node.Attribute("Include").Value.Replace(".Designer.cs", ".xaml");
    }
但如果我只在linq表达式的末尾添加
ToArray()
,问题就解决了


谁能解释一下为什么会这样?谢谢。

查询将在每个循环周期中进行评估

您正在更改
Include
值,因此该元素不再从查询中返回,因为它不匹配

A.Attribute("Include").Value.ToLower().Contains(".designer.cs")

通过对查询调用
ToArray
ToList
,循环枚举了一个固定的集合,因此您的操作不会产生影响。

OK,但为什么它会再次求值?