使用Linq展平/合并列表

时间:2012-08-29 01:25:59

标签: 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>

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

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

由于

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:4)

以下是使用查询语法的方法:

var query = from country in XDocument.Load(@"test.xml").Descendants("country")
            let countryName = new [] {(string)country.Attribute("name")}
            let cities = country.Elements("city").Select(x => (string)x)
            from place in countryName.Concat(cities)
            select place;