2010-01-17 76 views
2

我有一个包含关于产品的基本信息的XML文件,具有以下结构的XML复发的最高金额:获取使用LINQ

- products 
    - Id 
    - Price 
    - ManufacturerId 

而另外一个,约含厂商数据:

- manufacturers 
    - Id 
    - Name 

我想使用LINQ从products.xml文件中获得产品最多(制造商名称和产品数量)最多的3家制造商。

编辑:的products.xml文件看起来像这样:

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

的字段是两者的产品和制造商的文件属性。

回答

2

那么,你可以找到其中制造商是最重要的没有看他们是谁。然后您可以在第二个查询中获取详细信息。

例如,如果您要显示一些示例XML(例如,我们不知道制造商ID是属于某个属性还是元素),这将有所帮助。但它会是这样的:

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

谢谢你的快速答案!我添加了一个示例xml文件。我应该做的就是用'x.Attribute(“ManufacturerId”)'替换'x.Element(“ManufacturerId”)',对吧? – alex 2010-01-17 07:53:05

+0

差不多......现在编辑。 – 2010-01-17 08:32:04

+0

第二部分不按原样工作。我用这个代替:'var top3 = from manufacturer.Elements(“row”)中的元素其中top3Ids.Any(x => x.Id ==(string)element.Attribute(“Id”))select(string)element .Attribute(“Name”);' – alex 2010-01-17 11:16:54