Linq to XDocument Group by subset

I am looking for a linq query for Xdoc to group a subset of XML nodes. I was only able to get this working to return a subset of the data, but I need an entire XML document that is only transmitted with certain nodes.

<Root> <Elementname1> </Elementname1> <Elementname2> </Elementname2> <Elementname3 attrname="test1"> <Child> </Child> </Elementname3> <Elementname3 attrname="test1"> <Child> </Child> </Elementname3> </Root> 

This code:

 var result = from row in xDoc.Descendants("Elementname3") group row by (string)row.Attribute("attrname") into g select g.First(); 

returns:

 <Elementname3 attrname="test1"> <Child></Child> </Elementname3> 

Pending:

 <Root> <Elementname1> </Elementname1> <Elementname2> </Elementname2> <Elementname3 attrname="test1"> <Child> </Child> </Elementname3> </Root> 

I understand, since the descendant element starts with elementname3; just not sure how to set out the linq query to start with the root node and group as expected.

+4
source share
1 answer

Try the following:

 var result = new XDocument( new XElement("Root", from x in doc.Root.Elements() group x by new { x.Name, Attr = (string)x.Attribute("attrname") } into g select g.First() ) ); 
+6
source

Source: https://habr.com/ru/post/1389742/


All Articles