0

我有两个数据表,它们有不同的列,但一列是相同的。

我想获取新的 DataTable,其中包含 dt1 中不存在于 dt2 中的行。

我怎样才能使用 LINQ 呢?

那是我当前的代码,但它仅适用于具有相同列的数据表:

private void Delete_HPM_Deleted_Points(int YellowCard_Request_ID)
{
    DataTable dt_hpm_points_DB = DataAccessLayer.Get_YellowCard_Request_HPM_Points(YellowCard_Request_ID);
    //dt_hpm_points_DB.Columns.Remove("HPM_Tool_ID");
    //dt_hpm_points_DB.Columns.Remove("HPM_Point_Message");
    //dt_hpm_points_DB.Columns.Remove("HPM_Point_isDisabled");
    //dt_hpm_points_DB.Columns.Remove("HPM_Point_Comments");

    DataTable dt_hpm_points_Local = UserSession.Get_User_YC_HPM_Added_Points_DATATABLE();
    //dt_hpm_points_Local.Columns.Remove("HPM_Tool_ID");
    //dt_hpm_points_Local.Columns.Remove("HPM_Point_Message");

    //var rowsInFirstNotInSecond = dt_hpm_points_DB.Rows.Where(r1 => !dt_hpm_points_Local.Rows.Any(r2 => r1.ID == r2.ID));

    DataTable dt_points_to_remove = dt_hpm_points_DB.AsEnumerable().Except(dt_hpm_points_Local.AsEnumerable(), DataRowComparer.Default).CopyToDataTable();

    foreach (DataRow dr in dt_points_to_remove.Rows)
    {
        DataAccessLayer.Delete_YellowCard_Request_HPM_Point(YellowCard_Request_ID, dr["HPM_Point_ID"].ToString());
    }
}
4

1 回答 1

1

You can use Linq-To-DataSet with a "Left Outer Join":

var justInDT1 = from r1 in dt1.AsEnumerable()
                join r2 in dt2.AsEnumerable()
                on r1.Field<int>("PK_ID") equals r2.Field<int>("FK_ID") into GJ
                from subRow in GJ.DefaultIfEmpty()
                where subRow == null
                select r1;

How to: Perform Left Outer Joins (C# Programming Guide)

于 2013-01-08T11:42:41.957 回答