Remove A Row From A List Of DataRow

838 views Asked by At

I am using a Dictionary to create a key to a List Of DataRow. I want to iterate through each key and remove rows in the List. This will throw an out of range exception when I explicitly try to remove a row. How can I alter my code to accomplish this?

For Each g As KeyValuePair(Of [String], List(Of DataRow)) In grouped

   For Each row As DataRow In g.Value

         If CInt(segment(1)) <= 4 Then
             'THIS THROWS AN OUT OF RANGE EXCEPTION
             g.Value.Remove(row)
         End If  
   Next
Next

I only want to remove specific rows based on criteria. Can someone post an example? I am on an old browser the "add comment" function does not work

Can you show a code example of how to use a predicate based on row.Item("ID") with the RemoveAll function?

I tried this and am getting an exception

 g.Value.RemoveAll(Function(l) l.Item(Con.ID) Is l.Item(Con.ID).ToString)
2

There are 2 answers

0
Nick LaMarca On BEST ANSWER

I figured it out using a reverse For loop. I did not see an examlpe on how to use the RemoveAll. Please post an example if you have time

                For i As Integer = g.Value.Count - 1 To 0 Step -1
                            Dim row As DataRow = CType(g.Value(i), DataRow)

                            Dim segment() As String = row.Item(c._ID).ToString.Split("-"c)

                            If CInt(segment(1)) <= 4 Then
                                g.Value.Remove(row)
                            End If
                        Next i
3
Servy On

Use List.RemoveAll. Not only will this make the act of removing all of the items easier than trying to remove items in some form of looping construct, but it will be dramatically more efficient as the List can reorganize all of the items once at the end, rather than moving the items down one index at a time over and over.