Robert Robert - 6 months ago 37
Vb.net Question

ASP.Net VB - Linq to XML group by child element value

I need to group all values based on child element value. Below is example of my XML

<Matchday date="2016-05-09">
<Match id="1288348">
<Home id="13" name="club1"/>
<Away id="14" name="club2"/>
<Information>
<country>England</country>
</Information>
</Match>
<Match id="1288349">
<Home id="15" name="club3"/>
<Away id="16" name="club4"/>
<Information>
<country>England</country>
</Information>
</Match>
<Match id="1288350">
<Home id="17" name="club5"/>
<Away id="18" name="club6"/>
<Information>
<country>Italy</country>
</Information>
</Match>
<Match id="1288351">
<Home id="19" name="club7"/>
<Away id="20" name="club8"/>
<Information>
<country>Spain</country>
</Information>
</Match>
</Matchday>


I want to group by country, so the result will be like this :

England
1288348
1288349

Italy
1288350

Spain
1288351


How to do this using vb linq to xml query from code-behind.

Thanks

Answer

This is one possible way :

Dim result = data.Elements("Match") _
                 .GroupBy(Function(x) x.Element("Information").Element("country").Value)

For Each r As IGrouping(Of String, XElement) In result
    Console.WriteLine(r.Key)
    For Each m As XElement In r
        Console.WriteLine(m.@id)
    Next
Next

where data is an XElement declared as follow :

Dim data As XElement = <Matchday date="2016-05-09">
                       <Match id="1288348">
                           <Home id="13" name="club1"/>
                           <Away id="14" name="club2"/>
                           <Information>
                               <country>England</country>
                           </Information>
                       </Match>
                       <Match id="1288349">
                           <Home id="15" name="club3"/>
                           <Away id="16" name="club4"/>
                           <Information>
                               <country>England</country>
                           </Information>
                       </Match>
                       <Match id="1288350">
                           <Home id="17" name="club5"/>
                           <Away id="18" name="club6"/>
                           <Information>
                               <country>Italy</country>
                           </Information>
                       </Match>
                       <Match id="1288351">
                           <Home id="19" name="club7"/>
                           <Away id="20" name="club8"/>
                           <Information>
                               <country>Spain</country>
                           </Information>
                       </Match>
                   </Matchday>

and the output is as follow :

England
1288348
1288349
Italy
1288350
Spain
1288351
Comments