I have found strange behavior of IEnumerable. When i create a collection using Linq to XML and than loop the collection and change it’s elements, the collection size reduces by 1 on each passing through the loop. Here is what I am talking about:
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");
}
But if I add only ToArray<XElement>() to the end of the linq expression, problem is solved.
Can anyone explain me why is this happening? Thanks.
The query is evaluated on each loop cycle.
You’re changing the
Includevalue so the element is no longer returned from your query, as it doesn’t matchBy calling
ToArrayorToListon your query the loop enumerated a fixed collection, so your manipulation doesn’t impact.