我的LINQ到XML foreach循环正在尽早并意外终止。 没有例外。 这是怎么回事?
var doc = XDocument.Parse("<a><b>one</b><b>two</b></a>"); foreach(var element in doc.Root.Elements("b")) { element.ReplaceWith(XElement.Parse("<c>fixed</c>")); } doc.Dump();
给我
<a> <c>fixed</c> <b>two</b> </a>当我预料到
<a> <c>fixed</c> <c>fixed</c> </a>My linq to xml foreach loop is terminating early and unexpectedly. No exception raised. What's going on?
var doc = XDocument.Parse("<a><b>one</b><b>two</b></a>"); foreach(var element in doc.Root.Elements("b")) { element.ReplaceWith(XElement.Parse("<c>fixed</c>")); } doc.Dump();
Gives me
<a> <c>fixed</c> <b>two</b> </a>When I expected
<a> <c>fixed</c> <c>fixed</c> </a>最满意答案
我的LINQ到XML foreach循环正在尽早并意外终止。 这是怎么回事?
当您在同一个文档上对一个懒惰评估的查询进行迭代时,修改文档通常是一个糟糕的主意。 在某些情况下,它可能有效,但很难预测,而且我不知道这种行为是否被记录在案。 (想象一下,如果评估包含“当前”元素,并且每次都要求它的下一个兄弟元素 - 当元素已从文档中删除时,将不会有更多结果!)
如果你首先实现查询,它可以正常工作:
foreach(var element in doc.Root.Elements("b").ToList()) { // Removed the pointless XElement.Parse call; it's cleaner just to create // an element with the data you want. element.ReplaceWith(new XElement("c", "fixed")); }My linq to xml foreach loop is terminating early and unexpectedly. What's going on?
It's generally a bad idea to modify the document when you're iterating over a lazily evaluated query on the same document. In some cases it may work, but it's hard to predict, and I don't know whether the behaviour is even documented. (Imagine if the evaluation holds on to the "current" element, and asks it for its next sibling each time - there won't be any more results when the element has been removed from the document!)
If you materialize the query first, it works fine:
foreach(var element in doc.Root.Elements("b").ToList()) { // Removed the pointless XElement.Parse call; it's cleaner just to create // an element with the data you want. element.ReplaceWith(new XElement("c", "fixed")); }更多推荐
发布评论