Avatar of andre72
andre72

asked on 

Synchronize for DataTable (find duplicates)

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
.NET ProgrammingVisual Basic.NET

Avatar of undefined
Last Comment
x77
ASKER CERTIFIED SOLUTION
Avatar of Pratima
Pratima
Flag of India image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of x77
x77
Flag of Spain image

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

.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo