开发者

Get maximum amount of recurrences from XML using LINQ

I have a开发者_如何学Cn 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜