如何在Linq查询中添加Where不等于条件过滤含字符串的行
问题根因
- 原有查询仅校验了单元格值非空,未验证内容是否可转换为数值类型,遇到字符串时
Convert.ToInt32会抛出FormatException - Linq为延迟执行机制,你现有的
try块仅包裹了查询的定义逻辑,实际执行Su.ToList()绑定数据源的操作不在捕获范围内,异常抛出后会中断后续数据处理,仅能输出已计算完成的分组结果
修复方案
在数据分组前新增数值合法性校验,提前过滤掉包含非法值的行,从根源避免转换异常。修改后代码如下:
try { // 先校验label15的文本是否为合法数值,避免后续除法运算异常 if (!decimal.TryParse(label15.Text, out decimal totalBase) || totalBase == 0) { datagridview2.DataSource = null; return; } var Su = dataGridView1.Rows.Cast<DataGridViewRow>() // 过滤DataGridView自带的空白新增行 .Where(row => !row.IsNewRow) // 校验所有需要用到的单元格非空 .Where(row => row.Cells[2].Value != null && row.Cells[3].Value != null && row.Cells[8].Value != null) // 校验需要参与计算的单元格为合法int类型 .Where(row => int.TryParse(row.Cells[2].Value.ToString(), out _) && int.TryParse(row.Cells[3].Value.ToString(), out _)) .GroupBy(row => row.Cells[8].Value.ToString()) .Select(g => new { Gruppo = g.Key, Serie = g.Sum(row => Convert.ToInt32(row.Cells[2].Value)), Reps = g.Sum(row => Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[2].Value)), Percent = (g.Sum(row => Convert.ToDecimal(row.Cells[2].Value)) / totalBase) * 100 }); // 执行查询绑定数据源,放在try块内捕获可能的异常 datagridview2.DataSource = Su.ToList(); } catch (FormatException) { //MessageBox.Show("Formato non corretto"); datagridview2.DataSource = null; }
效果说明
修复后输入字符串的行将被直接过滤,不会中断整体计算逻辑,你给出的示例数据最终会输出group1、group3两组结果,符合预期。
内容的提问来源于stack exchange,提问作者Gabriele
相关产品推荐
相关产品推荐

