从另一个数据表中存在的数据表中删除行 [英] Delete rows from a data table that exists in another data table
问题描述
大家好,
如何在不使用for循环的情况下从另一个数据表中存在的数据表中删除行?因此,如果逐一比较,它会减慢过程。
Bcz两个数据表都有超过2万行,而用于循环,会减慢进程,所以任何其他方式删除?
如何一次删除?
什么我试过了:
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
推荐答案
不,没有使用<删除数据的机会For ... Next
loop。
注意:你正在使用For ... Next
循环3次。您只能将其缩短为一个循环。怎么样?通过Name
字段连接表以获取两个表的常见记录,然后从dt1
中删除它。
No, there's no chance to remove data without usingFor...Next
loop.
Note: you're usingFor...Next
loop 3 times. You can short it to one loop only. How? Join tables byName
field to get common records for both tables, then remove it fromdt1
.
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
但是!我会通过使用Transact SQL在服务器端执行此操作。请参阅: DELETE(Transact-SQL)| Microsoft Docs [ ^ ]
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)
这篇关于从另一个数据表中存在的数据表中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!