Synchronize for DataTable (find duplicates)

andre72
andre72 used Ask the Experts™
on
Hi,

I've a DataTables I need to convert to a new one.
The data are local loaded one and also I get more datas from a web service to one DT in memory.
Now I need to copy the data to an other DT but some records are duplicate.
There's a field called 'State' and value 1 has a higher priority than 0.
E.g.
Row0:
ID = 4711
Name = Test
State = 0
Row1:
ID = 4711
Name = Test
State = 1

In this case I like to get  4711 from Row1 as State has the higher priority there.

What do you suggest to copy my data into a new table excluding the duplicates with low priority?

Thanks,

Andre
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
x77

Commented:
Using PrimaryKey on DataTables, it is easy write code to do it.
Dim dt1, dt2, ndt As DataTable
        ndt = DirectCast(dt1.Clone, DataTable)
        Dim c1 = dt1.Columns("iD")
        Dim c2 = dt2.Columns("iD")
        Dim c3 = ndt.Columns("iD")
        dt1.PrimaryKey = New DataColumn() {c1}
        dt2.PrimaryKey = New DataColumn() {c2}
        ndt.PrimaryKey = New DataColumn() {c3}
        For Each r As DataRow In dt1.Rows
            Dim r2 = dt2.Rows.Find(r(c1))
            If r2 Is Nothing OrElse "0".Equals(r2("State")) Then
               ndt.ImportRow(r)
            Else
               ndt.ImportRow(r2)
            End If
        Next
        For Each r As DataRow In dt2.Rows
            If ndt.Rows.Find(r(c2)) IsNot Nothing Then Continue For 'row imported from dt1
            ndt.ImportRow(r)
        Next

Open in new window

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