C# 比较两个数据表并选择第二个表中不存在的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15713243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:42:05  来源:igfitidea点击:

Compare two DataTables and select the rows that are not present in second table

c#winformssystem.data.datatable

提问by Catalin

I have two DataTables and I want to select the rows from the first one which are not present in second one

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

For example:

例如:

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

Table B
  id   column
  1     data10
  3     data30

I want the result to be:

我希望结果是:

Table C
  id    column
  2      data2
  4      data4

采纳答案by Tim Schmelter

You can use Linq, especially Enumerable.Excepthelps to find id's in TableA that are not in TableB:

您可以使用 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();

You can also use Wherebut it'll be less efficient:

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

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

回答by sai

I got a solution which works without LINQ:

我得到了一个无需 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();

        }
    }
}

For more Visit http://microsoftdotnetsolutions.blogspot.in/2012/12/compare-two-datatables.html

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

回答by Abdul

You can use Linq Enumerable.ExceptMethod function to get diffence between two DataTable's Here i use firstDt and secondDt,remember both Dt's have the same structure.

您可以使用 Linq Enumerable.ExceptMethod 函数来获取两个 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
            }
        }

To read more on Enumerable.Except Method,Go to http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except(v=vs.110).aspx

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

and its Done!!!! Happy Coding.........

它完成了!!!!快乐编码........