使用Linq展平/合并列表

jzm*_*jzm 2 c# linq linq-to-xml

假设我有一个XML文件:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望它被夷为平地(这应该是最终的结果):

Australia
Brisbane
Melbourne
Sydney
England
Bristol
London
America
New York
Washington
Run Code Online (Sandbox Code Playgroud)

我试过这个:

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 })
    });
Run Code Online (Sandbox Code Playgroud)

但是这会返回一个嵌套列表query.像这样:

{ Australia, Cities { Brisbane, Melbourne, Sydney }},
{ England, Cities { Bristol, London }},
{ America, Cities { New York, Washington }}
Run Code Online (Sandbox Code Playgroud)

谢谢

Cha*_*ion 5

SelectMany应该在这里做的伎俩.

var result = 
    XDocument.Load(@"test.xml")
    .Descendants("country")
    .SelectMany(e => 
        (new [] { (string)e.Attribute("name")})
        .Concat(
            e.Elements("city")
            .Select(c => c.Value)
        )
    )
    .ToList();
Run Code Online (Sandbox Code Playgroud)