如何在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
相关产品推荐
相关产品推荐

