remove and return items from list matching predicate in csharp

In C#, you can remove and return items from a list that match a specific predicate using the List<T>.RemoveAll and List<T>.FindAll methods.

The RemoveAll method removes all items from the list that match the specified predicate and returns the number of items removed. Here's an example:

main.cs
List<int> myList = new List<int> { 1, 2, 3, 4, 5 };
int numRemoved = myList.RemoveAll(x => x % 2 == 0); // remove all even numbers
Console.WriteLine($"Removed {numRemoved} items from list."); // Output: Removed 2 items from list.
230 chars
4 lines

The FindAll method returns a new List<T> containing all items from the original list that match the specified predicate. Here's an example:

main.cs
List<string> myList = new List<string> { "apple", "banana", "cherry", "date", "elderberry" };
List<string> fruits = myList.FindAll(x => x.Length <= 5); // find all fruits with 5 or fewer characters
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
// Output:
// apple
// cherry
// date
303 chars
11 lines

You can see that the fruits list only contains items that match the predicate (apple, cherry, and date), while the original myList is unchanged.

related categories

gistlibby LogSnag