List RemoveAll ExampleEliminate all elements in a List that match a certain condition specified by a lambda expression.
This page was last reviewed on Dec 5, 2023.
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.
Step 2 We display the contents of the List after all elements greater than or equal to 4 were removed.
Step 3 Here we remove all elements with values not equal to 1—this leaves the List with just a single element (with value 1) in it.
Step 4 In this final 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 Module
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.
String Interpolation
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 Module
2 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.
This page was last updated on Dec 5, 2023 (new).
© 2007-2024 Sam Allen.