使用sum进行LINQ到XML分组
我目前正在使用此xml(这是一个很小的子集):使用sum进行LINQ到XML分组,linq,linq-to-xml,Linq,Linq To Xml,我目前正在使用此xml(这是一个很小的子集): 我会先变换,然后分组/求和: var query = from element in doc.Descendants("order") select new { Customer = (int) element.Element("customer"), Total = (decimal) element.Element("total") } into
我会先变换,然后分组/求和:
var query = from element in doc.Descendants("order")
select new { Customer = (int) element.Element("customer"),
Total = (decimal) element.Element("total") }
into order
group order.Total by order.Customer into g
select new { Customer = g.Key, Total = g.Sum() };
foreach (var result in query)
{
Console.WriteLine("customer {0} with a total of {1}",
result.Customer, result.Total);
}
(当然,您也可以用点表示法来完成这一切。)
customer 1035 with a total of 15.6
customer 1036 with a total of 5.6
var query = from element in doc.Descendants("order")
select new { Customer = (int) element.Element("customer"),
Total = (decimal) element.Element("total") }
into order
group order.Total by order.Customer into g
select new { Customer = g.Key, Total = g.Sum() };
foreach (var result in query)
{
Console.WriteLine("customer {0} with a total of {1}",
result.Customer, result.Total);
}