-1

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)
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

2 Answers2

2

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • This is absolutely correct, but can anyone explain how `RemoveAll` can help here, I think OP want to only remove certain items? – Bolu Nov 20 '14 at 16:38
  • 1
    @Bolu And `RemoveAll` accepts a predicate to use in determining which item should be removed, which, is exactly what the OP wants. He already has a predicate to determine which items to keep right in his question. `Clear` would be the method to just unconditionally make the list empty. – Servy Nov 20 '14 at 16:39
  • Thank you, don't know this before. and sorry if my comment above caused one -1 here. – Bolu Nov 20 '14 at 16:45
1

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
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152