比较 C# 中的两个数据表并查找新的、匹配的和非匹配的记录

Comparing two datatables in C# and finding new, matching and non-macting records

我有两个数据表,Datatable1 和Datatable2。 Datatable1 是另一个的子集。我想找出哪些行是新的,哪些是匹配的,哪些是不匹配的。想要在 Datatable1 中添加一个新行,其值是新的、匹配的和不匹配的。请建议一种优化方法。

例如: 数据表 1:

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name1", typeof(string));
table.Columns.Add("Name2", typeof(string));
//New
table.Rows.Add(25, "Ciya", "David");
table.Rows.Add(51, "Kiya", "Cecil");
//Matching 
table.Rows.Add(50, "Bina", "Cecil");
//Non matching
table.Rows.Add(21, "Riya", "Janet");
table.Rows.Add(10, "Rita", "Christoff");

数据表2:

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name1", typeof(string));
table.Columns.Add("Name2", typeof(string));

table.Rows.Add(10, "Lisa", "Christoff");
table.Rows.Add(21, "Combivent", "Janet");
table.Rows.Add(50, "Bina", "Cecil");

您可以尝试使用可用于 Intersect, Except 等可枚举类型的 Linq 方法。这是一个这样做的例子。

// Get matching rows from the two tables
IEnumerable<DataRow> matchingRows = table1.AsEnumerable().Intersect(table2.AsEnumerable());

// Get rows those are present in table2 but not in table1
IEnumerable<DataRow> rowsNotInTableA = table2.AsEnumerable().Except(table1.AsEnumerable());