tags:

views:

111

answers:

1

I have an xml file containing basic information about products, with the following structure:

 - products
   - Id 
   - Price
   - ManufacturerId

And another one, containing data about manufacturers:

 - manufacturers
   - Id
   - Name

I'd like to get the top 3 manufacturers with the most products (manufacturer name and number of products) from the products.xml file using LINQ.

Edit: the products.xml file looks like this:

<products>
  <row Id="1" Price="1.00" ManufacturerId="3"/>
  <row Id="1" Price="0.99" ManufacturerId="2"/>
</products>

The fields are attributes for both the products and manufacturers files.

+2  A: 

Well, you can find out which manufacturers are the top ones without looking at who they are. You can then get the details in a second query.

It would help if you would show some sample XML - we don't know whether the manufacturer ID is in an attribute or an element, for example. But it would be something like:

var top3Ids = products.Elements("row")
                      .GroupBy(x => (string) x.Attribute("ManufacturerId"))
                      .Select(group => new { Id = group.Key,
                                             Count = group.Count() })
                      .OrderByDescending(x => x.Count)
                      .Select(x => x.Id)
                      .Take(3)
                      .ToList();

var top3 = from element in manufacturers.Elements("row")
           where top3Ids.Contains((string) element.Attribute("Id"))
           select (string) element.Attribute("Name");
Jon Skeet
Thank you for the fast answer! I added a sample xml file. What I should basically do is replace `x.Element("ManufacturerId")` with `x.Attribute("ManufacturerId")`, right?
alex
Nearly... editing now.
Jon Skeet
The second part doesn't work as is. I used this instead: `var top3 = from element in manufacturers.Elements("row") where top3Ids.Any(x => x.Id == (string)element.Attribute("Id")) select (string)element.Attribute("Name");`
alex
@alex: Oops - there's a better fix than that. Will edit the first query.
Jon Skeet