How to compare column names in two different datatables and fetch the matched one into new datatable?

I have two datatables dt1, and dt2 and I want to check the similar column headers between two tables if it has the same header then print the dt1 column in new dt .

Hi @Soundarya_Guduri

you can use the following expression to check if two datatable columns are same or not

(From dc In dt1.Columns.Cast(Of System.Data.DataColumn) Select dc.ColumnName).ToArray().All(function(x) (From dc In dt2.Columns.Cast(Of System.Data.DataColumn) Select dc.ColumnName).ToArray().Contains(x))

Use this in if and it then do what ever steps you need after them.

Here basically I am taking column names of both datatables as Array and comparing them

cheers

Hello @Soundarya_Guduri

Are you trying to compare 2 datatable and to get similar and dissimilar data from it?

Thanks

Assign Activity:
arrCommonColNames | String() - String Array =

dt1.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).Intersect(dt2.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName)).ToArray

the condition check can be interpreted in multiple directions:

  • can have commons, but also differents
  • no uncommons are allowed

One technique to check that all columns are the same and no uncommon col exists:

arrCol1Names = dt1.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray
arrCol2Names = dt2.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray
isMatching = arrCol1Names.Intersect(arrCol2Names).Count = arrCol1Names.Length AndAlso arrCol1Names.Length = arrCol2Names.Length 
1 Like

A lightweight check for all colnames are present, same order, same names can be done by the following:

arrCol1Names = dt1.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray
arrCol2Names = dt2.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray
isMatching = arrCol1Names.SequenceEqual(arrCol2Names)

Thankyou for your response
Input file
Input.xlsx (14.3 KB)
Sheet1 =dt1
sheet2=dt2
sheet = newdt → need to get Common header names and including data
could you please send me the workflow

do a start with:

Assign activity:

arrCol1Names = dt1.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray

Assign activity:

arrCol1Names = dt1.Columns.Cast(Of DataColumn).Select(Function (x) x.ColumnName).toArray

Assign activity:

arrCommonNames = arrCol1Names.Intersect(arrCol2Names).toArray

If Activity: arrCommonNames.Any()
Then: dtResult = dt1.DefaultView.ToTable(false, arrCommonNames )
Else: dtResult = dt1.Clone()

Thank you @ppr

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.