Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Linq展平/合并列表_C#_Linq_Linq To Xml - Fatal编程技术网

C# 使用Linq展平/合并列表

C# 使用Linq展平/合并列表,c#,linq,linq-to-xml,C#,Linq,Linq To Xml,假设我有一个XML文件: <locations> <country name="Australia"> <city>Brisbane</city> <city>Melbourne</city> <city>Sydney</city> </country> <country name="England">

假设我有一个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>
我试过这个:

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 })
    });
但这将返回
查询
中的嵌套列表。像这样:

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

我们应该在这里表演

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

下面是一种使用查询语法的方法:

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