LINQ to XML与sum分组

时间:2012-01-31 18:52:17

标签: linq linq-to-xml

我目前正在使用这个xml(这是一个小子集):

<?xml version="1.0" encoding="UTF-8"?>
<orders>
    <order>
        <customer><![CDATA[1035]]></customer>
        <total><![CDATA[10]]></total>
    </order>
    <order>
        <customer><![CDATA[1036]]></customer>
        <total><![CDATA[5.6]]></total>
    </order>
    <order>
        <customer><![CDATA[1035]]></customer>
        <total><![CDATA[5.6]]></total>
    </order>
</orders>

我试图找出是否有办法按客户对此进行分组并总计总数。

当我遍历分组时,我会:

customer 1035 with a total of 15.6
customer 1036 with a total of 5.6

1 个答案:

答案 0 :(得分:2)

我先转换,然后分组/求和:

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);
}

(当然,你也可以点符号完成所有这些。)