Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten/Merge List using Linq

Lets say I have an XML file:

<locations>
    <country name="Australia">
        <city>Brisbane</city>
        <city>Melbourne</city>
        <city>Sydney</city>
    </country>
    <country name="England">
        <city>Bristol</city>
        <city>London</city>
    </country>
    <country name="America">
        <city>New York</city>
        <city>Washington</city>
    </country>
</locations>

I want it flattened to (this should be the final result):

Australia
Brisbane
Melbourne
Sydney
England
Bristol
London
America
New York
Washington

I've tried this:

var query = XDocument.Load(@"test.xml").Descendants("country")
    .Select(s => new
    {
        Country = (string)s.Attribute("name"),
        Cities = s.Elements("city")
            .Select (x => new { City = (string)x })
    });

But this returns a nested list inside query. Like so:

{ Australia, Cities { Brisbane, Melbourne, Sydney }},
{ England, Cities { Bristol, London }},
{ America, Cities { New York, Washington }}

Thanks

like image 780
mnsr Avatar asked Mar 17 '26 01:03

mnsr


1 Answers

SelectMany should do the trick here.

var result = 
    XDocument.Load(@"test.xml")
    .Descendants("country")
    .SelectMany(e => 
        (new [] { (string)e.Attribute("name")})
        .Concat(
            e.Elements("city")
            .Select(c => c.Value)
        )
    )
    .ToList();
like image 149
ChaosPandion Avatar answered Mar 18 '26 13:03

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!