For Each Dr As DataRow In InvoiceDT.Rows
Dim DrResult As Array = PaymentInvoiceDT.Select("Amount='" & Dr("Amount").ToString() & "'")
If DrResult.Length > 0 Then
''some code
Else
InvoiceDT.Rows.remove(Dr)
End If
Next
Run Code Online (Sandbox Code Playgroud)
它给出了错误,因为当您在datatable中更改某些内容时,其索引会发生更改.
Tri*_*dus 18
您将无法在For Each循环中执行此操作,因为当您删除某些内容时,该集合已更改,您无法再枚举它.
你需要的是一个反向的For循环.
For i as Integer = Invoice.Rows.Count -1 to 0 Step -1
Dim DrResult As Array = PaymentInvoiceDT.Select("Amount='" & Invoice.Rows(i).("Amount").ToString() & "'")
If DrResult.Length > 0 Then
'some code
Else
InvoiceDT.Rows.remove(InvoiceDT.Rows(i))
End If
Next
Run Code Online (Sandbox Code Playgroud)
即使在删除行时,这仍然有效,因为您没有触摸的行没有更改其索引并且不使用枚举.
Sai,它失败了,因为你不应该在所有表行中循环时真正删除行.
你可以做的一个例子,在C#中是这样的:
DataTable dt = CreateDataSource();
DataRow[] rows = (from t in dt.AsEnumerable().Cast<DataRow>()
where t.Field<int>("ID") == 1
select t).ToArray();
foreach (DataRow row in rows)
{
dt.Rows.Remove(row);
}
Run Code Online (Sandbox Code Playgroud)
因此,当您看到第一个选择要使用LINQ删除的所有行时,您只在结果行上循环并从源表中删除它们.
抱歉没有时间在VB.NET中写这个,但我希望这个想法应该清楚.
| 归档时间: |
|
| 查看次数: |
39210 次 |
| 最近记录: |