I have two data tables and I want to grab only one column from one of the data tables and add it to the other one. How can I accomplish this in a simple way with LINQ queries, without using a For Each?
Example:
DT1 has column “Name” with two rows
DT2 has the same number of rows, but does not have column “Name.” I want column “Name” and all row values to be copied into DT2.
Is there a common value between the two tables that you’re trying to match up? Or don’t you care about the order of the rows in the two datatables?
If there is a common value you need to match on, then use Join Data Table.
If you don’t care about the order, then just use Filter Data Table to keep only the column you want in DT1, and then use Merge Data Table to copy it to DT2.
Assumption: Project is set to Windows Compatibility
For learning purpose see below LINQ Approach (DataTable Reconstruction Strategy)
Assign Activity:
DT2Enhanced = dt2.Clone
Prepare DT2Enhanced by adding the Name column at the end with add DataColumn
Assign activity:
DT2Enhanced=
(From i in Enumerable.Range(0,dt2.AsEnumerable.Rows.Count
Let ra1 = dt2.Rows(i).ItemArray
Let n = dt1.Rows(i)("Name")
Let ra = ra1.Append(n).ToArray
Select r = DT2Enhanced.Rows.Add(ra)).CopyToDataTable
Feel free to reorder the DT2Enhanced columns by DT2Enhanced.DefaultView.ToTable(False, arrColNames)
arrColNames is String Array with all ColNames in new order