Thomas
Thomas

Reputation: 5998

LINQ to XML grouping with sum

I am currently working with this xml (this is a small subset):

<?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>

I am trying to figure out if there is a way to group this by customer and sum the total.

When I iterate through groupings I would have:

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

Upvotes: 1

Views: 406

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503419

I would first transform, then group/sum:

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

(You could do all of this in dot notation as well, of course.)

Upvotes: 2

Related Questions