Click here to Skip to main content
14,690,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

how to delete rows from a data table that exists in another data table without using for loop ? so if compare one by one , it slow the process.

Bcz both data table got more then 2 lakhs rows,while use for loop, it will slow the process, so any other way to remove ?

How to delete with one shot ?

What I have tried:

Dim dt1 As New DataTable()
dt1.Columns.Add("Name")
dt1.Rows.Add("Apple")
dt1.Rows.Add("Banana")
dt1.Rows.Add("Orange")
 
Dim dt2 As New DataTable()
dt2.Columns.Add("Name")
dt2.Rows.Add("Apple")
dt2.Rows.Add("Banana")
 
Dim rows_to_remove As New List(Of DataRow)()
For Each row1 As DataRow In dt1.Rows
    For Each row2 As DataRow In dt2.Rows
        If row1("Name").ToString() = row2("Name").ToString() Then
            rows_to_remove.Add(row1)
        End If
    Next
Next
 
For Each row As DataRow In rows_to_remove
    dt1.Rows.Remove(row)
    dt1.AcceptChanges()
Next


For example i gave 3 and 2 datas, but actually it retrieve  from database more than 2 lakhs data.

Regards,
Aravind
Posted
Updated 21-Mar-18 22:23pm
v2

1 solution

No, there's no chance to remove data without using For...Next loop.
Note: you're using For...Next loop 3 times. You can short it to one loop only. How? Join tables by Name field to get common records for both tables, then remove it from dt1.
Dim rows_to_remove = From a In dt1.AsEnumerable() Join b In dt2.AsEnumerable() On a.Field(Of String)("Name") Equals b.Field(Of String)("Name")
	Select a
'returns:
'Apple 
'Banana 


You can use Linq Except[^] method too:
Dim rows_to_remove = dt2.AsEnumerable.Except(dt1.AsEnumerable())
'returns:
'Apple 
'Banana 


But! I'd do that on server side by using Transact SQL. See: DELETE (Transact-SQL) | Microsoft Docs[^]

DELETE 
FROM Table1 
WHERE FieldName1 IN (SELECT FieldName1 FROM Table2)
   
v2
Comments
Aravindba 22-Mar-18 6:42am
   
yes thank you, why i am using data table, bcz run time icneed to remove and show, that's y i bind in datatable and remove from there, instead of deleting in main table in sql.

Any way thanks for reply 1 and 2 work form me.
Maciej Los 22-Mar-18 8:58am
   
Great!
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900