【问题标题】:Compare 2 DataTable C# [duplicate]比较 2 DataTable C# [重复]
【发布时间】:2015-12-08 01:46:38
【问题描述】:

我有 2 个数据表,它们的数据相似,但 id 字段完全不同。数据列也有不同的名称 这就是我的意思:

Table1

 id      dataIn1
010      Data000
123      Data1   
222      Data2
323      Data4
443      Data6

Table2

 id      dataIn2
551      Data1
676      Data2
111      Data3
625      Data4
444      Data5
665      Data6

我想要一个新的 DataTable3,它在 Table2 中有数据,但在 Table1 中没有。请注意,Table1 中有一行,Table2 中没有,但我不在乎。

Table3
 id      dataIn3
111      Data3
444      Data5

我已经尝试了这些方法:

tb2.Merge(tb1);
DataTable tb3 = tb2.GetChanges(); 

但是tb3返回了null

这返回了一个数据表,但行错误

var notIn1 = tb2.AsEnumerable().Select(r => r.Field<string>("dataIn2"))
                .Except(tb1.AsEnumerable().Select(r => r.Field<string>("dataIn2")));

DataTable tb3 = (from row2 in tb2.AsEnumerable()
                 join row3 in notIn1
                 on row2.Field<string>("dataIn2") equals row3
                 select row2).CopyToDataTable();

【问题讨论】:

  • 我确实在 StackOverlow 上查看了一些解决方案,但它们对我不起作用。
  • 哦,实际上其中一种解决方案奏效了。我只是不知何故错过了它。

标签: c# datatable


【解决方案1】:

你可以这样做:

IEnumerable<int> val_table1 = Table1.AsEnumerable().Select(val=> (int)val["dataIn1"]);
IEnumerable<int> val_table2  = Table2.AsEnumerable().Select(val=> (int)val["dataIn2"]);
IEnumerable<int> val_notinTable1= val_table2.Except(val_table1);

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 2020-09-28
    • 2011-12-17
    • 2011-05-26
    相关资源
    最近更新 更多