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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.