我发现了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");
}
但如果我只在linq表达式的末尾添加ToArray<XElement>()
,问题就解决了。
任何人都可以解释我为什么会这样吗?感谢。
答案 0 :(得分:5)
在每个循环周期中评估查询。
您正在更改Include
值,因此不再从查询中返回该元素,因为它不匹配
A.Attribute("Include").Value.ToLower().Contains(".designer.cs")
通过在查询中调用ToArray
或ToList
,循环枚举了一个固定的集合,因此您的操作不会受到影响。