@Lance James , based on my test, I find a method to compare two datatbales and add items in table 2 that don't exist in table 1 to table1.
First of all , based on my test, DataTable.Merge can not get your goal, because it may contains the duplicate item.
For example:
DataTable table1=new DataTable();
table1.Columns.Add("Name");
table1.Columns.Add("Age");
table1.Columns.Add("Id");
table1.Rows.Add("test1", 22, 1002);
DataTable table2 = new DataTable();
table2.Columns.Add("Name");
table2.Columns.Add("Age");
table2.Columns.Add("Id");
table1.Merge(table2);
I set the same datarow for the two datatables, but the result is the following:
Obviously, it is not you wanted data. The result should be only one row instead of two duplicated rows.
Therefore, I recommend that you could use the following method to compare two datatables.
Usage:
var comparer = new CustomComparer();
DataTable dtUnion = table1.AsEnumerable()
.Union(table2.AsEnumerable(), comparer).CopyToDataTable<DataRow>();
Extension Class:
class CustomComparer : IEqualityComparer<DataRow>
{
#region IEqualityComparer<DataRow> Members
public bool Equals(DataRow x, DataRow y)
{
return ((string)x["Name"]).Equals((string)y["Name"]);
}
public int GetHashCode(DataRow obj)
{
return ((string)obj["Name"]).GetHashCode();
}
#endregion
}
Hope this could help you.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.