0
我很惊讶地看到,并非所有我在下面的代码元素被迭代:迭代的IEnumerable与linq2xml
IEnumerable<XElement> dataStorageGroupElements = document.Descendants().Where(x => "Xms.Common.DataStorageGroup" == (string)x.Attribute("NodeType"));
int counter = 0;
foreach (XElement dataStorageGroupElement in dataStorageGroupElements)
{
Console.WriteLine($"Counter={counter++}, NbElements={dataStorageGroupElements.Count()}");
XElement newParent = GetNewParentForDataStorageGroup(dataStorageGroupElement);
dataStorageGroupElement.Remove();
newParent.Add(dataStorageGroupElement);
}
输出是:
Counter=0, NbElements=12
Counter=1, NbElements=12
Counter=2, NbElements=12
Counter=3, NbElements=12
Counter=4, NbElements=12
Counter=5, NbElements=12
Counter=6, NbElements=12
更改代码来执行枚举与ToArray()修复此问题:
IEnumerable<XElement> dataStorageGroupElements = document.Descendants().Where(x => "Xms.Common.DataStorageGroup" == (string)x.Attribute("NodeType")).ToArray();
用上面的代码计数器正在增加ent to 11.
为什么有些元素被跳过描述为here。但为什么NbElements总是12?是否仅在第一次评估?
您的意思是linq to xml? – Cosmin
@Cosmin是的,我确实:/修正了 – Philippe