I have found strange behavior of IEnumerable. When i create a colle开发者_JAVA技巧ction 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 Include
value so the element is no longer returned from your query, as it doesn't match
A.Attribute("Include").Value.ToLower().Contains(".designer.cs")
By calling ToArray
or ToList
on your query the loop enumerated a fixed collection, so your manipulation doesn't impact.
精彩评论