Linq using Group by
I want to get the Category
based total of the following
<?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>
....
What is the modification needed to achieve it in the following ?(nothing is returned in my query)
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")) };
Your sample data shows an attribute of "category" but you're using "Category" in the query.
It looks like the query should nearly work other than that - although again I would strongly urge you to use decimal
rather than double
for the price.
EDIT: As Konamiman's now-deleted answer says, you need to group by the attribute value rather than the attribute itself. This code works (and uses decimal):
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"))
};
精彩评论