比较两个DataTable并选择第二个表中不存在的行

时间:2013-03-29 23:55:53

标签: c# winforms system.data.datatable

我有两个DataTables,我想从第一个中选择第二个不存在的行

例如:

Table A
  id   column
  1     data1
  2     data2
  3     data3
  4     data4

Table B
  id   column
  1     data10
  3     data30

我希望结果是:

Table C
  id    column
  2      data2
  4      data4

3 个答案:

答案 0 :(得分:17)

您可以使用Linq,尤其是Enumerable.Except帮助查找TableA中不在TableB中的ID:

var idsNotInB = TableA.AsEnumerable().Select(r => r.Field<int>("id"))
        .Except(TableB.AsEnumerable().Select(r => r.Field<int>("id")));
DataTable TableC = (from row in TableA.AsEnumerable()
                   join id in idsNotInB 
                   on row.Field<int>("id") equals id
                   select row).CopyToDataTable();

您也可以使用Where,但效率会降低:

DataTable TableC = TableA.AsEnumerable()
    .Where(ra =>  !TableB.AsEnumerable()
                        .Any(rb => rb.Field<int>("id") == ra.Field<int>("id")))
    .CopyToDataTable();

答案 1 :(得分:4)

我找到了一个没有LINQ的解决方案:

public DataTable CompareDataTables(DataTable first, DataTable second)
{
    first.TableName = "FirstTable";
    second.TableName = "SecondTable";

    //Create Empty Table
    DataTable table = new DataTable("Difference");

    try
    {
        //Must use a Dataset to make use of a DataRelation object
        using (DataSet ds = new DataSet())
        {
            //Add tables
            ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

            //Get Columns for DataRelation
            DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

            for (int i = 0; i < firstcolumns.Length; i++)
            {
                firstcolumns[i] = ds.Tables[0].Columns[i];
            }

            DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

            for (int i = 0; i < secondcolumns.Length; i++)
            {
                secondcolumns[i] = ds.Tables[1].Columns[i];
            }

            //Create DataRelation
            DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

            ds.Relations.Add(r);

            //Create columns for return table
            for (int i = 0; i < first.Columns.Count; i++)
            {
                table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
            }

            //If First Row not in Second, Add to return table.
            table.BeginLoadData();

            foreach (DataRow parentrow in ds.Tables[0].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r);
                if (childrows == null || childrows.Length == 0)
                    table.LoadDataRow(parentrow.ItemArray, true);
            }

            table.EndLoadData();

        }
    }
}

更多访问http://microsoftdotnetsolutions.blogspot.in/2012/12/compare-two-datatables.html

答案 2 :(得分:0)

你可以使用Linq Enumerable.Except 方法函数来获取两个DataTable之间的差异。在这里我使用firstDt和secondDt,记住两个Dt具有相同的结构。

 var EntriesNotInB = firstDt.AsEnumerable().Select(r => r.Field<string>("abc")).Except(secondDt.AsEnumerable().Select(r => r.Field<string>("abc")));

        if (EntriesNotInB.Count() > 0)
        {
            DataTable dt = (from row in firstDt.AsEnumerable()join id in EntriesNotInB  on row.Field<string>("abc") equals id select row).CopyToDataTable();
            foreach (DataRow row in dt.Rows)
            {
              /////Place your code to manipulate on datatable Rows
            }
        }

要了解有关Enumerable.Except方法的更多信息,请转到http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except(v=vs.110).aspx

及其完成!!!!快乐编码.........