2009-11-11 45 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")) 
      };