Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two DataTables without duplicate values for a column

Tags:

c#

datatable

I have two DataTables like

DataTable1(With default values)-

Tag |Alias|Value  |Type
abc |""   |default|default
xyz |""   |default|default

DataTable2(With actual values)-

Tag |Alias |Value  |Type
abc |test  |12    |Real

Now if I use DataTable.Merge() I get the rows with both default and actual values for tag abc. I need only the actual values for a particular tag present in 2nd table, if not the default values from 1st table. How do i do this?

like image 449
user2806116 Avatar asked Jan 11 '23 03:01

user2806116


1 Answers

Just add a primary key constraint to the Tag column before merging.

Example:

var dt1 = new DataTable();
var prime1 = dt1.Columns.Add("Tag", typeof(string));
dt1.Columns.Add("Value", typeof(string));
dt1.Rows.Add(new object[]{"abc", "default"});
dt1.Rows.Add(new object[]{"xyz", "default"});
dt1.PrimaryKey = new DataColumn[]{ prime1 };

var dt2 = new DataTable();
var prime2 = dt2.Columns.Add("Tag", typeof(string));
dt2.Columns.Add("Value", typeof(string));
dt2.Rows.Add(new object[]{"abc", "12"});
dt2.PrimaryKey = new DataColumn[]{ prime2 };

dt1.Merge(dt2);

dt1 now looks like:

enter image description here

like image 200
sloth Avatar answered Jan 28 '23 17:01

sloth