C# IEnumerable在更改时减少';什么内容?
我发现了许多奇怪的行为。当我使用Linq to XML创建一个集合,然后循环该集合并更改其元素时,每次通过循环时,集合大小都会减少1。以下是我所说的: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").
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,但为什么它会再次求值?