使用LINQ按多个XML节点分组

时间:2013-04-11 17:17:07

标签: xml linq

<myDocument>
    <country code="US">
        <region code="CA">
            <city code="Los Angeles">
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </city>
            <city>
                ...
            </city>
        </region>
        <region>
            ...
        </region>
    </country>
    ...
</myDocument>

我希望最终得到一个唯一的“值”(a,b,c等)列表,其中包含countryCode,regionCode,cityCode列表,其中显示了该值出现的所有位置。如何使用LINQ to XML完成这种选择?

Result
======
Key : a
Value : List of country/region/city codes
    US, CA, Los Angeles
    US, CA, San Fransisco
    US, AL, Hatford

Key : b
    etc

1 个答案:

答案 0 :(得分:2)

This it how it turns out:

var grouped = from country in doc.Elements("country")
              from region in country.Elements("region")
              from city in region.Elements("city")
              from value in city.Elements("value")

              group value by new
              {
                   Value = value.Value,
                   Country = country.Attribute("code").Value,
                   Region = region.Attribute("code").Value,
                   City = city.Attribute("code").Value
              };

Dictionary<string, List<Tuple<string, string, string>>> dic = (from grouping in grouped
select new KeyValuePair<string, List<Tuple<string, string, string>>>(
     grouping.Key.Value,
     (from occurence in grouping 
      select new Tuple<string, string, string>(
          grouping.Key.Country, 
          grouping.Key.Region, 
          grouping.Key.City)
      ).ToList()))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

就是这样。痛苦的屁股格式正确。希望有所帮助。 它创建了一个字典,其中Key是Value,Value是一个包含Country,Region,City of the值的元组列表。