比较两个不同数据表中的ID

时间:2014-07-04 09:35:05

标签: c# datatable

我有两个数据表,我正在显示第二个dt的记录现在我想只显示第二个dt中那些在第一个dt

中不可用的记录
for (int i = 0; i < dt.Rows.Count; i++)
{
    if (dtCheck.Select("LedgerID =" + dt.Rows[i]["ID"]).Length > 0)
    {
        string check = (History.Select("LedgerID = " + dt.Rows[i]     
        ["ID"] +  "").Length > 0 ? "checked=\"checked\"" : "");
        ret.Append("<tr><td><input type=\"checkbox\" " + check + " 
       name=\"SelectedLedger\" onclick=\"var ctl = 
       document.getElementById('SelectedLedgerID');if(this.checked)
      {ctl.value = ctl.value + '" + dt.Rows[i]["ID"] + ",';}else{ctl.value 
      = ctl.value.replace('" + dt.Rows[i]["ID"] + ",', '');}\">" + 
      dt.Rows[i]["Title"] + "</td></tr>");
    }
}

我这样做但是没有用。

2 个答案:

答案 0 :(得分:0)

尝试应用两个DataTables的交集,如

using System.Data;

public static class DataTableExtensions
{
    public static IEnumerable<DataRow> Intersect(this DataTable table, DataTable other)
    {
        return table.AsEnumerable().Intersect(other.AsEnumerable());
    }

    public static IEnumerable<DataRow> Intersect(this DataTable table, DataTable other, IEqualityComparer<DataRow> comparer)
    {
        return table.AsEnumerable().Intersect(other.AsEnumerable(), comparer);
    }
}

答案 1 :(得分:0)

怎么样

for (int i = 0; i < seconddt.Rows.Count; i++)
{
    bool isRecord = firstdt.AsEnumerable()
                    .Any(x => Convert.ToInt32(x["ID"]) == 
                              Convert.ToInt32(seconddt.Rows[i]["ID"]));
    if (isRecord)
    {
        //Add Record.
    }
}