1

I have following piece of code which removes the rows from the DataTable based upon custom_id as "Y" (i.e. remove the row if value for the key custom_id is "Y" in the dictionary). Now that I have very few records in list fldListWithUnlimitedDataEnabled and relatively huge records in DataTable objDt, is there a way to delete the specific rows (as done in objRow.Delete()) from objDt, so that I don't have to traverse entire DataTable for few records?

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
djv
  • 15,168
  • 7
  • 48
  • 72
Abhishek
  • 539
  • 5
  • 25
  • I know this isn't the answer you're looking for, but in your example you want Contains, not Equals. – dwilliss Nov 06 '17 at 14:58
  • 1
    Thanks...edited the question – Abhishek Nov 06 '17 at 15:04
  • [This](https://stackoverflow.com/questions/1591771/datatable-how-to-conditionally-delete-rows) should give you an idea. It's c#, but the concept is the same for vb.net. – MatSnow Nov 06 '17 at 15:11

1 Answers1

1

If objDt is a part of a strongly-typed DataSet and custom_id is the primary key of the DataTable, it will have a FindBycustom_id method that will find the row.

The name of the function is auto-generated to be FindBy followed by the primary key name(s). Then you can iterate through your list of keys, find the row, and delete them.

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

If that's not an available option, you can always use Select

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