更改内容时,IEnumerable会减少吗?

Val*_*ale 2 c# ienumerable linq-to-xml

我发现了IEnumerable的奇怪行为.当我使用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");
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我只添加ToArray<XElement>()到linq表达式的末尾,问题就解决了.

谁能解释我为什么会这样?谢谢.

Jak*_*cki 5

在每个循环周期中评估查询.

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

A.Attribute("Include").Value.ToLower().Contains(".designer.cs")
Run Code Online (Sandbox Code Playgroud)

通过调用ToArrayToList查询循环枚举固定集合,因此您的操作不会影响.