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

如何在C# DataTable中比较B列与A列值并展示结果?

C#实现DataTable中B列值小于对应A列值的统计并显示

直接修改原代码的筛选条件即可实现需求,核心是在Where子句中同时获取A、B两列的对应值,判断Column_B < Column_A的逻辑,同时修正原代码里变量名不匹配的问题:

// 统计Column_B值小于对应Column_A值的行数
int count = Dt.AsEnumerable()
              .Where(row => row.Field<decimal>("Column_B") < row.Field<decimal>("Column_A"))
              .Count();
// 将结果显示在Label控件中
lbCount.Text = count.ToString();

补充说明:

  • 确保Column_A和Column_B的数据类型确实是decimal,如果实际类型不同(比如int、double),需要把Field<decimal>改成对应的数据类型
  • 如果列可能存在空值(DBNull),可以先判断值是否有效,避免抛出异常:
    int count = Dt.AsEnumerable()
                  .Where(row => !row.IsNull("Column_A") && !row.IsNull("Column_B") 
                                && row.Field<decimal>("Column_B") < row.Field<decimal>("Column_A"))
                  .Count();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:01:28