【问题标题】:C# how to compare the values of two Datatables with a toleranceC#如何将两个数据表的值与容差进行比较
【发布时间】:2019-12-13 08:19:39
【问题描述】:

我正在开发一个读取两个数据表的工具。 这些数据表具有相同的 ID(ForeignKey) 但值不同。
例如:
表一

ID Length Height
1    2.5    2.4
2    3.4    1.9
3    1.1    2.2

表2

ID Length Height
1    2.5    2.0
2    3.2    1.7
3    1.0    2.2

如何将这些表格与公差进行比较?所以它识别出两个数据表中的 ID 相同的地方,例如长度相差 0.1 和高度相差 0.2 是否可以?

完美的解决方案是一张看起来像这样的桌子

    ID Length Height
1    ok        ok
2    not ok    ok
3    not ok    not ok

有没有办法做到这一点? 感谢问候

【问题讨论】:

    标签: c# datatables compare


    【解决方案1】:

    这里可以用例来比较两列

    前:

    select case when (2=2) then 'ok' else 'not ok' end
    

    【讨论】:

      【解决方案2】:

      你可以使用下面的case语句

      select t1.ID
          CASE WHEN ABS(t1.LENGTH-t2.LENGTH)<0.1 then 'ok' else 'not ok 'end,
          CASE WHEN ABS(t1.HEIGHT-t2.HEIGHT)<0.2 then 'ok' else 'not ok 'end
        from TABLE1 t1 join Table2 t2 on t1.ID = t2.ID
      

      【讨论】:

      • 如何在 c# 中对数据表应用 sql 查询?
      【解决方案3】:
      select tbl1.Id,
      CASE when ABS(tbl1.Length-tbl2.Length)<=0.1 then 'OK' else 'Not OK' END,
      CASE when ABS(tbl1.Height-tbl2.Height)<=0.2 then 'OK' else 'Not OK' END 
      from table1 tbl1 inner join table2 tbl2 on tbl1.Id=tbl2.Id
      

      如果您想比较两个数据表,请使用 LinQ

      Datatable dtNew = (from dt1 in datatble1.AsEnumerable()
                           join dt2 in datatable2.AsEnumerable()
                           on dt1[id].ToString() = dt2[id].ToString()
                          .where()
                          .Select()
                        ).CopyToDatatable()
      

      相应地应用 where 条件。 或者您可以参考 (https://forgetcode.com/csharp/1508-comparing-two-datatables-and-returning-a-datatable-by-matching-one-or-more-columns-using-linq)

      【讨论】:

      • 如何在 c# 中对数据表应用 sql 查询?
      • 请解释您的回答如何帮助解决问题。仅发布代码答案通常无助于回答问题。
      • 它是否帮助您解决了您的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多