我希望通过比较两个DataTables来获得不匹配的记录
例如:
表1
TransID BookingID BookingStatus BookingType
1 11 Y Paid
2 12 N UnPaid
3 13 N Paid
表1
TransID BookingID BookingStatus BookingType
1 11 Y Paid
2 12 Y UnPaid
4 14 Y Paid
我想通过使用列TransID和BookingID来比较上面两个表,我希望结果如下
[无与伦比的记录]
TransID BookingID BookingStatus(Table 1) BookingType(Table 1) BookingStatus(Table 2) BookingType(Table 2)
2 12 N UnPaid Y Unpaid
3 13 N Paid NA(NULL) NA(NULL)
4 14 NA(NULL) NA(NULL) Y Paid
如何使用LINQ ?????????
实现此目的我尝试通过以下方法比较数据表:
var result = from dataRows1 in dtTable1.AsEnumerable()
join dataRows2 in dtTable2.AsEnumerable() on new { TransID = dataRows1["TransID"], BookingID = dataRows1["BookingID"] } equals new { TransID = dataRows2["TransID"], BookingID = dataRows2["BookingID"] } into rows
from row in rows.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows1["TransID"],
dataRows1["BookingID"],
dataRows1["BookingStatus"],
dataRows1["BookingType"],
row==null? "NA" : row["BookingType"]
}, false);
//==== copy output of result into datatable named 'dtResult' =============================
result.CopyToDataTable(); // This point records will be loaded in dtResult data table
这只给了我匹配的记录。
答案 0 :(得分:0)
以下代码有效,并提供您要求的结果集。虽然我采取了自由的事情 1.在您的加入条件下,您只拥有TransId和BookingId,但在您的样本中无法比拟'数据,看起来您也希望预订状态不同,所以我将其添加到我的联接中 - 您可以匹配您想要的任何字段。 2.在BookingType之后选择有一个额外的列时,不确定scoop是什么,似乎是多余的,但同样,您可以根据需要格式化输出。 但就查询而言,你基本上需要一个完整的外部联接,Linq并不真正支持,但是下面的代码将为你提供两个联合的外连接,做同样的事情。
var result = (from d1 in dtTable1.AsEnumerable()
join d2 in dtTable2.AsEnumerable() on new { TransID = d1["TransID"], BookingID = d1["BookingID"], BookingStatus =d1["BookingStatus"] } equals new { TransID = d2["TransID"], BookingID = d2["BookingID"], BookingStatus =d2["BookingStatus"] } into leftJoin
from d2 in leftJoin.DefaultIfEmpty()
where d2 == null
select dtResult.LoadDataRow(new object[]
{
d1["TransID"],
d1["BookingID"],
d1["BookingStatus"],
d1["BookingType"]
}, false)).Union(
from dt2 in dtTable2.AsEnumerable()
join dt1 in dtTable1.AsEnumerable() on new { TransID = dt2["TransID"],
BookingID = dt2["BookingID"] } equals new { TransID = dt1["TransID"], BookingID = dt1["BookingID"] } into rightJoin
from dt1 in rightJoin.DefaultIfEmpty()
where dt1 == null
select dtResult.LoadDataRow(new object[]
{
dt2["TransID"],
dt2["BookingID"],
dt2["BookingStatus"],
dt2["BookingType"]
}, false));
result.CopyToDataTable();