0
<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 等)的列表,其中包含国家代码、区域代码、城市代码的列表,显示该值出现的所有位置。如何使用 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
4

1 回答 1

2

结果是这样的:

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

这样做。痛苦地格式化它。希望有帮助。它创建了一个字典,其中键是值,值是包含所有值出现的国家、地区、城市的元组列表。

于 2013-04-11T17:21:42.413 回答