我有以下场景:
表A有50条记录,表B有2条记录。
我需要定义一个新的表,比如TableDiff,它应该包含表a中不存在于表B 中的48条记录
我的问题是,表A和表B不完全相同,但我有字段rowId
,它存在于两个表中,我需要使用它进行比较。
单向使用Enumerable.Except
和Enumerable.Join
:
var aIDs = TableA.AsEnumerable().Select(r => r.Field<int>("RowID"));
var bIDs = TableB.AsEnumerable().Select(r => r.Field<int>("RowID"));
var diff = aIDs.Except(bIDs);
DataTable tblDiff = (from r in TableA.AsEnumerable()
join dId in diff on r.Field<int>("RowID") equals dId
select r).CopyToDataTable();
以下是linq到对象的"左联接"方法:
DataTable tblDiff = (from rA in TableA.AsEnumerable()
join rB in TableB.AsEnumerable()
on rA.Field<int>("RowID") equals rB.Field<int>("RowID") into joinedRows
from ab in joinedRows.DefaultIfEmpty()
where ab == null
select rA).CopyToDataTable();
using System.Data.DataSetExtensions
var tableAIds = tableA.AsEnumerable().Select(row => (int)row["rowId"]);
var tableBIds = tableB.AsEnumerable().Select(row => (int)row["rowId"]);
var resultantIds = tableAIds.Except(tableBIds);
现在用于再次创建数据表
DataTable diff = from myRow in tableA.AsEnumerable()
join rIDS resultantIds in myRow.Field<int>("rowId") equals rIDS
select myRow).CopyToDataTable()