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.
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.
RemoveAll()
and pass a lambda Function to it, which returns true for each element greater than or equal to 4.List
after all elements greater than or equal to 4 were removed.List
with just a single element (with value 1) in it.For Each
loop, we again print the elements contained within the List
collection.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
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!
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.