我试图根据给定的列名查找两个数据表之间的差异。我看不到我在做什么错,但是当我传递两个不同的数据表时,没有任何结果。
dt1 dt2
ID Percent ID Percent
--- ------- --- -------
1 100 1 100
2 100 2 100
.. ... .. ...
50 0 50 20
.. ... .. ...
所以,我叫GetTableDiff(dt1,dt2,“ Percent”),而不是得到一行(ID:50,Percent: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;
}
答案 0 :(得分:3)
您需要加入"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;