2009-11-11 63 views
1

我想要得到的Category基于共有以下LINQ的使用组由

<?xml version="1.0" encoding="utf-8" ?> 
- <Data> 
- <Products> 
    <Product ProductId="1001" ProductName="p1" category="A1" 
    ProductPrice="123.45" /> 

    <Product ProductId="1002" ProductName="p2" category="B1" 
    ProductPrice="100.45" /> 

    <Product ProductId="1003" ProductName="p3" category="A1" 
    ProductPrice="223.45" /> 

    <Product ProductId="1004" ProductName="p4" category="B1" 
    ProductPrice="200.45" /> 
    </Products> 
.... 

什么是实现它在下面?(没有什么是 返回我的查询)

XDocument doc = XDocument.Load("Product.xml"); 

var sum = from p in doc.Descendants("Product") 
      group p by p.Attribute("Category") 
      into g 
      select new { category = g.Key, 
      total = g.Sum(p =>(double)p.Attribute("ProductPrice")) }; 
需要修改

回答

3

您的示例数据显示“类别”的属性,但您在查询中使用“类别”。

它看起来像查询应接近工作比其他 - 虽然我再次强烈督促您使用decimal而非double的价格。

编辑:Konamiman现在删除的答案说,你需要按属性,而不是属性本身。此代码工作(并使用十进制):

var sum = from p in doc.Descendants("Product") 
      group p by p.Attribute("category").Value 
      into g 
      select new { category = g.Key, 
         total = g.Sum(p => (decimal) p.Attribute("ProductPrice")) 
      };