LINQ to XML 使用总和进行分组

发布于 2024-12-31 22:51:17 字数 762 浏览 1 评论 0原文

我目前正在使用这个 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与往事干杯 2025-01-07 22:51:17

我会首先进行变换,然后进行分组/求和:(

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

当然,您也可以用点表示法完成所有这些操作。)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文