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

C#使用LINQ计算DataGridView多列x前数值的总和及平均值

问题:DataGridView多列提取数值求和与求平均

需求:计算DataGridView中多列的数值总和并求平均值,列值格式为类似“3x8”的字符串,需提取每个值中x前面的数字(如3)进行求和。当前代码得到的是字符串拼接结果(例如两列都是3x8时得到33,期望正确数值和为6)。

示例数据

GroupVal1 to sumVal2 to sum
group13x83x8
group11x55x5
group32x202x10

当前问题代码

var Su = dataGridView1.Rows.Cast<DataGridViewRow>()
      .Where(row => row.Cells["Group"].Value != null)
      .Where(row => row.Cells["Val1"].Value != null)
      .GroupBy(row => row.Cells["Group"].Value.ToString())
    .Select(g => new
    {
        Group = g.Key,
        Sum = g.Sum(row => {
            int sum = 0;
            if (row.Cells["week1"].Value.ToString().Contains("x"))
            {
                Debug.WriteLine("true condition 1");
                sum += (Convert.ToInt32(row.Cells[1].Value.ToString().Split('x')[0] + row.Cells[2].Value.ToString().Split('x')[0])) ;
                return sum;
            }
            else {
                Debug.WriteLine("true else");
                return 0; }
        })

解决方案

问题根源

代码中错误地将两个拆分后的字符串直接拼接(row.Cells[1].Value.ToString().Split('x')[0] + row.Cells[2].Value.ToString().Split('x')[0]),再转换为整数。比如"3"+"3"会变成字符串"33",转int后得到33,而非预期的3+3=6。

修正实现

1. 提取前缀数字的辅助函数

先写一个通用函数处理单个单元格的数值提取,避免重复代码,同时处理空值、格式错误等异常情况:

private int GetPrefixNumber(object cellValue)
{
    if (cellValue == null) return 0;
    string valueStr = cellValue.ToString().Trim();
    if (string.IsNullOrEmpty(valueStr) || !valueStr.Contains("x")) return 0;
    
    string prefix = valueStr.Split('x')[0];
    return int.TryParse(prefix, out int number) ? number : 0;
}

2. 修正后的查询代码

var result = dataGridView1.Rows.Cast<DataGridViewRow>()
    // 确保参与计算的列都不为空
    .Where(row => row.Cells["Group"].Value != null 
                 && row.Cells["Val1 to sum"].Value != null 
                 && row.Cells["Val2 to sum"].Value != null)
    .GroupBy(row => row.Cells["Group"].Value.ToString())
    .Select(g => new
    {
        Group = g.Key,
        // 每组的总和:每行两列前缀数相加后再累加
        TotalSum = g.Sum(row => 
            GetPrefixNumber(row.Cells["Val1 to sum"].Value) + 
            GetPrefixNumber(row.Cells["Val2 to sum"].Value)),
        // 每组的平均值:用double避免整数除法精度丢失
        Average = g.Average(row => 
            (double)(GetPrefixNumber(row.Cells["Val1 to sum"].Value) + 
            GetPrefixNumber(row.Cells["Val2 to sum"].Value)))
    });

说明

  • 辅助函数GetPrefixNumber统一处理单元格值的提取逻辑,降低代码冗余,同时避免因空值、格式错误引发的异常。
  • Sum逻辑改为分别提取两列的前缀数字并转换为整数后相加,再对每组进行求和,得到正确的数值总和。
  • Average使用double类型计算,避免整数除法导致的平均值精度丢失(比如总和为15、共2行时,整数除法会得到7而非7.5)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:57:42