我正在尝试使用LINQ语句比较两个DataTable
我的表的结构是这样的
EmpId -- FirstName -- LastName -- DOB
Emp是唯一键(整数),DOB是Date,rest是字符串。
有两个DataTables进入
SourceTable和TargetTable
TargetTable可能具有相同数量的记录或更少。 FirstName,LastName或DOB的某些值可能不同。
这是没有左外连接的查询,但无法获取其余的源记录。
var matched = from dtSource in sourceTable.AsEnumerable()
join dtTarget in targetTable.AsEnumerable() on dtSource.Field<int>("empid") equals dtTarget.Field<int>("empid")
where dtSource.Field<string>("firstname") != dtTarget.Field<string>("firstname")
|| dtSource.Field<string>("lastname") != dtTarget.Field<string>("lastname")
|| dtSource.Field<DateTime>("dob") != dtTarget.Field<DateTime>("dob")
select dtSource;
我正在尝试进行左外连接,以便获取目标数据表中不存在的其余记录。
这就是我的尝试
var join = from dtSource in source
join dtTarget in target
on dtSource.Field<int>("EmpId") equals dtTarget.Field<int>("EmpId")
into outer
where
dtSource.Field<string>("firstname") != dtTarget.Field<string>("firstname")
|| dtSource.Field<string>("lastname") != dtTarget.Field<string>("lastname")
|| dtSource.Field<DateTime>("dob") != dtTarget.Field<DateTime>("dob")
from dtEmpSal in outer.DefaultIfEmpty()
select new
{
FirstName = dtSource.Field<string>("FirstName") == null ? "" : dtSource.Field<string>("FirstName"),
LastName = dtSource.Field<string>("LastName") == null ? "" : dtSource.Field<string>("LastName"),
DOB = dtSource.Field<DateTime>("dob") == null ? DateTime.Today : dtSource.Field<DateTime>("dob")
};
当然我做错了,因为我无法编译,因为我无法访问where子句中的dtTarget。我做错了什么,不知道是什么。
编辑:
这就是我的源DataTable的样子
这就是我的Target的样子
在我的情况下,结果集应该包含empIds 1,6,7的emp记录,依此类推。注1是不同的(姓氏),2,3,4,5包含在目标DataTable中。
截屏显示我的烦恼:
https://www.dropbox.com/s/145ba6oa59fstdc/screencap.wmv
我发现很难调试这个:(
答案 0 :(得分:0)
这是帮助我的原因
public static dynamic GetAllDifferences (DataTable sourceTable,DataTable targetTable)
{
var source = sourceTable.AsEnumerable();
var target = targetTable.AsEnumerable();
var noMatchInSource = from dtSource in source
join dtTarget in target on dtSource.Field<int>("empid") equals dtTarget.Field<int>("empid")
where dtSource.Field<string>("firstname").Equals(dtTarget.Field<string>("firstname"))
&& dtSource.Field<string>("lastname").Equals(dtTarget.Field<string>("lastname"))
&& dtSource.Field<DateTime>("dob").Equals(dtTarget.Field<DateTime>("dob"))
select dtSource;
var result =
from sourceDataRow in sourceTable.AsEnumerable()
where !(from noMatchDataRow in noMatchInSource
select noMatchDataRow.Field<int>("empid"))
.Contains(sourceDataRow.Field<int>("empid"))
select sourceDataRow;
return result;
}