Peter Morris
Peter Morris

Reputation: 23224

Use LINQ to group by multiple XML nodes

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

I want to end up with a list of unique "value" (a, b, c, etc) with a list of countryCode, regionCode, cityCode showing all of the places where that value appears. How would this kind of select be done using 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

Upvotes: 0

Views: 492

Answers (1)

CSharpie
CSharpie

Reputation: 9467

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

That does it. Pain in the ass to format it proper. Hope that helps. It creates a dictionary where the Key is the Value and the Value is a List of tuples containing Country, Region, City of all that values occurences.

Upvotes: 2

Related Questions