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

在CSHTML中按类别求和生成HTML表格及汇总问题咨询

在CSHTML中按类别求和并生成带总计的HTML表格

核心思路

先通过Razor代码对数据按类别分组,计算每个类别的金额总计,再汇总所有类别的总和,最后渲染成HTML表格。优先在后端/Razor代码块完成数据聚合,比前端累计更可靠高效。

完整实现示例

假设你有如下数据模型(可替换为你实际的实体类):

public class Transaction
{
    public string Category { get; set; }
    public decimal Amount { get; set; }
}

在CSHTML中编写以下代码:

1. 数据处理(Razor代码块)

@{
    // 模拟数据源(替换为你实际的数据库查询或业务数据)
    var transactions = new List<Transaction>
    {
        new Transaction { Category = "餐饮", Amount = 50.2m },
        new Transaction { Category = "餐饮", Amount = 35.8m },
        new Transaction { Category = "交通", Amount = 20m },
        new Transaction { Category = "购物", Amount = 120m },
        new Transaction { Category = "交通", Amount = 15m }
    };

    // 按类别分组并计算每个类别的总计
    var categoryTotals = transactions
        .GroupBy(t => t.Category)
        .Select(g => new 
        {
            Category = g.Key,
            TotalAmount = g.Sum(t => t.Amount)
        })
        .ToList();

    // 计算所有类别的总合计
    var grandTotal = categoryTotals.Sum(ct => ct.TotalAmount);
}

2. 渲染HTML表格

<table border="1" cellpadding="8" cellspacing="0">
    <thead>
        <tr>
            <th>类别</th>
            <th>类别总计</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in categoryTotals)
        {
            <tr>
                <td>@item.Category</td>
                <td>@item.TotalAmount.ToString("C")</td> <!-- 格式化金额为货币格式 -->
            </tr>
        }
        <!-- 总合计行 -->
        <tr style="font-weight: bold;">
            <td>总合计</td>
            <td>@grandTotal.ToString("C")</td>
        </tr>
    </tbody>
</table>

关键说明

  • 分组求和:使用GroupBy按类别分组,再用Sum计算每组的金额总和,这是实现类别总计的核心,避免了前端累计的误差。
  • 总合计计算:基于分组后的结果再次求和,无需重复遍历原始数据,提升处理效率。
  • 金额格式化:ToString("C")会自动适配当前区域的货币格式,也可替换为ToString("N2")仅保留两位小数。

如果数据来自数据库(如EF Core),可直接在查询阶段完成分组求和,减少内存消耗:

// EF Core示例:直接从数据库分组查询
var categoryTotals = _dbContext.Transactions
    .GroupBy(t => t.Category)
    .Select(g => new 
    {
        Category = g.Key,
        TotalAmount = g.Sum(t => t.Amount)
    })
    .ToList();

内容的提问来源于stack exchange,提问作者abdulkareem amoora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:16:03