IEnumerable 在更改其内容时会减少?
我发现 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");
}
但是如果我仅将 ToArray
添加到 linq 表达式的末尾,问题就解决了。
谁能解释一下为什么会发生这种情况?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查询在每个循环周期进行评估。
您正在更改
Include
值,以便不再从查询中返回该元素,因为它与调用
ToArray
或ToList
不匹配在您的查询中,循环枚举了一个固定集合,因此您的操作不会产生影响。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 matchBy calling
ToArray
orToList
on your query the loop enumerated a fixed collection, so your manipulation doesn't impact.