基于给定列的两个数据表之间的差异

Difference between two datatables based on given column

我试图根据给定的列名找出两个数据表之间的区别。我在这里看不出我做错了什么,但是当我传递两个不同的数据表时,我没有得到任何结果。

    dt1                  dt2
ID    Percent        ID    Percent
---   -------        ---   -------
1     100            1     100
2     100            2     100
..    ...            ..    ...
50    0              50    20
..    ...            ..    ...

所以,我调用 GetTableDiff(dt1, dt2, "Percent") 而不是获取一行(ID:50,百分比:20),我什么也没得到。

public static DataTable GetTableDiff(DataTable dt1, DataTable dt2, string sColumn)
{     
    DataTable dtDiff = new DataTable();
    try
    {
        var diff = from r1 in dt1.AsEnumerable()
                    join r2 in dt2.AsEnumerable()
                        on r1.Field<int>(sColumn)
                        equals r2.Field<int>(sColumn) into g
                    where !g.Any() // get only rows which do not have joined rows from dt2
                    select r1;

        if (diff.Count() > 0)
            dtDiff = diff.CopyToDataTable();
    }
    catch (Exception ex)
    {
    }
    return dtDiff;
}

您需要加入 "ID" 而不是 sColumn 字符串,然后比较您期望的列名称。

from r1 in dt1.AsEnumerable()
                join r2 in dt2.AsEnumerable()
                    on r1.Field<int>("ID")
                    equals r2.Field<int>("ID") 
                where r2.Field<int>(sColumn) != r1.Field<int>(sColumn) 
                select r1;