Compare two tables

Sandiya
Sandiya used Ask the Experts™
on
Hi All,

I want a asp.net ,vb code to compare two datatables and dynamically generate alter table for the missing columns .
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dirk HaestProject manager

Commented:
You can use linq. Small example attached.

    Private Sub compareTables()
        Dim Table1 As DataTable = New DataTable("Customers")
        Table1.Columns.Add("Name", Type.GetType("System.String"))
        Table1.Columns.Add("Firstname", Type.GetType("System.String"))
        Table1.Columns.Add("Street", Type.GetType("System.String"))
        Table1.Columns.Add("HouseNumber", Type.GetType("System.String"))
        Table1.Columns.Add("PostalCode", Type.GetType("System.String"))

        Dim Table2 As DataTable = New DataTable("Customers2")
        Table2.Columns.Add("Name", Type.GetType("System.String"))
        Table2.Columns.Add("Firstname", Type.GetType("System.String"))
        Table2.Columns.Add("State", Type.GetType("System.String"))

        Dim firstquery = From col In Table1.Columns Select col.columnName
        Dim notinsecondtable = From col In Table2.Columns Where Not firstquery.Contains(col.columnName)
    End Sub

Open in new window


The last query will tell you that you have a column (namely state) in your second datatable that is not in your first datatable
Most Valuable Expert 2012
Top Expert 2014
Commented:

Author

Commented:
Thanks All

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial