Linq XML descendants being lost on enumeration

anon

New Member
I have an XML document like this\[code\]<root> <item id="1" creator="me"> <childA>1</childA> <childB>2</childB> </item> <item id="2" creator="me"> <childA>1</childA> <childB>3</childB> <childB>4</childB> </item></root>\[/code\]I'm trying to find duplicate items, then again duplicate child items for the duplicate items with logic like this\[code\]XDocument XmlRoot //whatever...you get the point// Get item nodesvar items = XmlRoot.Descendants("item");// Find duplicate items keys using creator attributevar duplicateItemKeys = items.GroupBy(x => x.Attribute("creator").Value).Where(g => g.Count() > 1).Select(g => g.Key);foreach(var duplicateItemKey in duplicateItemKeys){ // Get the duplicate item XML elements using the duplicate keys var duplicateItems = items.Where(x => x.Attribute("creator").Value =http://stackoverflow.com/questions/11371200/= duplicateToucheKey) .OrderBy(xelement => xelement.Attribute("CreatedOn").Value);}\[/code\]This works, however there is a problem later when I try to use duplicateItems. Any time it enumerates (like in a foreach duplicateItems) the first item looses the context of it's children. The second one is just fine.So for example, later in code I say\[code\]var allItemB = new List<XElement>();foreach (duplicateItem in duplicateItems) { allItemB.AddRange(duplicateItem.Descendants("childB"));}\[/code\]I expect "allItemB" to contain 2 on the first pass, then 234 on the second. What ends up happening is that it only contains 34 because once the duplicateItems array is enumerated the first XElement looses it's children.Does anyone know how to fix this?
 
Back
Top