【问题标题】:Compare ID in two different datatables比较两个不同数据表中的 ID
【发布时间】:2014-07-04 09:35:04
【问题描述】:

我有两个数据表,我正在显示来自第二个 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>");
    }
}

我正在这样做,但它不起作用。

【问题讨论】:

  • 呃....什么乱七八糟的代码。也许尝试格式化它?

标签: c# datatable


【解决方案1】:

尝试应用两个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);
    }
}

【讨论】:

    【解决方案2】:

    怎么样

    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.
        }
    }
    

    【讨论】:

    • 两个 dt 都有多个记录,这与第一个 dt 相比如何
    • for (int i = 0; i 0)我是这样做的,但它不工作 { } }
    • @DineshChauhan:你有什么问题?你被困在哪里了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多