可以说我有一个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>


我希望将其展平到(这应该是最终结果):

Australia
Brisbane
Melbourne
Sydney
England
Bristol
London
America
New York
Washington


我已经试过了:

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 })
    });


但这会在query中返回一个嵌套列表。像这样:

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


谢谢

最佳答案

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();

关于c# - 使用Linq展平/合并列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12169718/

10-13 08:48