基于多列的数据表差异

时间:2018-07-25 13:51:42

标签: c# linq datatable

我试图根据多个列查找两个数据表之间的差异。我已经根据一栏(如下)成功做到了:

//return all rows in dt1 but not in dt2 based on column name

public 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<string>(sColumn).Trim().ToLower()
                        equals r2.Field<string>(sColumn).Trim().ToLower() into g
                    where !g.Any() // get only rows which do not have joined rows from dt2
                    select r1;

        dtDiff = diff.CopyToDataTable();
    }
    catch (Exception ex)
    {
    }
    return dtDiff;
}

1 个答案:

答案 0 :(得分:0)

一种方法是使用简单比较,即:

var diff = from r1 in dt1.AsEnumerable()
     where !dt2.AsEnumerable()
               .Any( r2 => r1.Field<string>("col1") == r2.Field<string>("col1Inr2") ||
                           r1.Field<string>("col2") == r2.Field<string>("col2Inr2"))
     select r1;

但是,根据实际需求,您可以使用IEqualityComparer创建更好的方法。对于示例check my blog sample.