Search code examples
.netvb.netlinqxelement

How do I sort elements by the attributes of the elements' children?


For an XElement like

<a>
 <b><c id="2"></b>
 <b><c id="3"></b>
 <b><c id="1"></b>
</a>

Is there a way to get a list of <b> ordered by <c> id values?

I unsuccessfully tried

bElements.OrderBy(function b As XElement) b.Elements.Attributes("id")) and bElements.OrderBy(function b As XElement) b.Elements.ToString).


Solution

  • Depending on your precise needs, you could do this:

    bElements.OrderBy(function (b As XElement) b.Elements.Attributes("id").First().Value)
    

    Or this:

    bElements.OrderBy(function (b As XElement) b.Elements.First().Attribute("id").Value)
    

    Or even this:

    bElements.OrderBy(function (b As XElement) b.<c>.@id)