【问题标题】:Delete multiple records with LINQ in VB.NET在 VB.NET 中使用 LINQ 删除多条记录
【发布时间】:2018-04-18 17:30:35
【问题描述】:

我有以下代码,它根据custom_id 将行从DataTable 中删除为“Y”(即,如果键custom_id 的值在dictionary 中为“Y”,则删除该行) .现在我的列表fldListWithUnlimitedDataEnabled 中的记录很少,而DataTable objDt 中的记录相对较大,有没有办法从objDt 中删除特定的行(如objRow.Delete() 中所做的那样),这样我就不会必须遍历整个DataTable 以获得很少的记录?

Dim objRow As DataRow
Dim customFlds As Dictionary(Of String, String) = m_objCmnFncs.getCustomFlsdWithUnlimitedDataIndicator(strOrgId)
Dim fldListWithUnlimitedDataEnabled As List(Of String) = (From kv As KeyValuePair(Of String, String) In customFlds
                                                          Where kv.Value.Equals("Y")
                                                          Select kv.Key).ToList
If fldListWithUnlimitedDataEnabled.Count > 0 Then

    For Each objRow In objDt.Rows
        //The below condition effects the performance
        If fldListWithUnlimitedDataEnabled.Contains(objRow("custom_id")) Then
            objRow.Delete()
        End If
    Next
End If

【问题讨论】:

  • 我知道这不是您要寻找的答案,但在您的示例中,您想要包含,而不是等于。
  • 谢谢...编辑了问题
  • This 应该会给你一个想法。是c#,但是vb.net的概念是一样的。

标签: vb.net dictionary


【解决方案1】:

如果 objDt 是强类型 DataSet 的一部分,并且 custom_id 是 DataTable 的主键,它将有一个 FindBycustom_id 方法来查找行。

函数的名称自动生成为 FindBy 后跟主键名称。 然后你可以遍历你的键列表,找到行,然后删除它们。

For Each id in fldListWithUnlimitedDataEnabled
    Dim objRow = objDt.FindBycustom_id(id)
    if objRow IsNot Nothing Then objRow.Delete()
Next

如果这不是可用的选项,您可以随时使用 Select

For Each id in fldListWithUnlimitedDataEnabled
    Dim objRows = objDt.Select("custom_id = '" & id & "'")  
    For Each row in objRows 
        row.Delete()
    Next
Next

【讨论】:

  • 不幸的是,它不是强类型数据集的一部分,其中 custom_id 可以是主键。
  • Select 的方法有点用处
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多