You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在cshtml页面中对列表按类别分组执行sum求和操作

问题原因

你现有代码的核心错误是foreach循环中每次遍历分类分组都直接覆盖totalPorCategoria变量的值,最终只会输出最后一个分类的小计和,没有实现按分类汇总后求和的逻辑。


对应解决方案

根据两类常见需求,分别提供可用代码:

场景1:需要展示每个分类的单独合计金额

<span style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important ; font-size: 18px !important ; color: #4CAF50 !important ; font-weight: 700 !important ; float: right !important">
    各分类合计:
    <span style="color: #212121 !important">
        @{
            var agrupamentoPorCategoria = Model.itens.GroupBy(c => c.idCategoria);
        }
        @foreach (var itensPorCategoria in agrupamentoPorCategoria)
        {
            <div>
                分类@itensPorCategoria.Key:@itensPorCategoria.Sum(s => s.vSubTotal).ToString("N2")
            </div>
        }
    </span>
</span>

场景2:需要先按分类求和、再累加所有分类合计得到总金额(即你预期的5,557.55结果)

<span style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important ; font-size: 18px !important ; color: #4CAF50 !important ; font-weight: 700 !important ; float: right !important">
    总金额:
    <span style="color: #212121 !important">
        @{
            var totalPorCategoria = Model.itens
                .GroupBy(c => c.idCategoria)
                .Sum(g => g.Sum(s => s.vSubTotal))
                .ToString("N2");
        }
        @totalPorCategoria
    </span>
</span>

内容的提问来源于stack exchange,提问作者Thiago Corrêa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:24:04