RemoveAll. Suppose a List contains one or more elements that are not needed—we can remove these elements with RemoveAll. Only one function call is needed.
By removing many elements with a function call, we can avoid confusing loops. We must specify a lambda expression when calling RemoveAll, but the syntax in VB.NET is easy to understand.
Example. To test the RemoveAll method on the List generic type, we first need a List to modify. Here we create a List and remove elements from it.
Step 1 We invoke RemoveAll() and pass a lambda Function to it, which returns true for each element greater than or equal to 4.
Module Module1
Sub Main()
Dim list = New List(Of Integer)({ 1, 2, 3, 4, 5, 6 })
' Step 1: call RemoveAll with a predicate lambda expression.
list.RemoveAll(Function (item)
Return item >= 4
End Function)
' Step 2: display results.
For Each value in list
Console.WriteLine($"REMOVEALL: {value}")
Next
' Step 3: remove all values not equal to 1.
list.RemoveAll(Function (item)
Return item <> 1
End Function)
' Step 4: display results again.
For Each value in list
Console.WriteLine($"REMOVEALL AGAIN: {value}")
Next
End Sub
End ModuleREMOVEALL: 1
REMOVEALL: 2
REMOVEALL: 3
REMOVEALL AGAIN: 1
Return value. The RemoveAll Function returns an Integer indicating how many elements were removed. Here we remove 2 strings with value "bird" and the value returned is 2.
Module Module1
Sub Main()
Dim list = New List(Of String)({ "bird", "bird", "dog" })
' Remove all "bird" elements from list, and print count of items removed.
Dim removed = list.RemoveAll(Function (item)
Return item = "bird"
End Function)
Console.WriteLine($"{removed} birds were removed!")
End Sub
End Module2 birds were removed!
Summary. Removing multiple elements from a List is a complex task when For-loops are used. But RemoveAll, a Function on the List type, helps and simplifies this task.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.