I was looking for the same thing. I wanted to do some error logging on the items that I was removing. Since I was adding a whole bunch of validation rules, the remove-and-log call should be as concise as possible.
I've made the following extension methods:
public static class ListExtensions
{
/// <summary>
/// Modifies the list by removing all items that match the predicate. Outputs the removed items.
/// </summary>
public static void RemoveWhere<T>(this List<T> input, Predicate<T> predicate, out List<T> removedItems)
{
removedItems = input.Where(item => predicate(item)).ToList();
input.RemoveAll(predicate);
}
/// <summary>
/// Modifies the list by removing all items that match the predicate. Calls the given action for each removed item.
/// </summary>
public static void RemoveWhere<T>(this List<T> input, Predicate<T> predicate, Action<T> actionOnRemovedItem)
{
RemoveWhere(input, predicate, out var removedItems);
foreach (var removedItem in removedItems) actionOnRemovedItem(removedItem);
}
}
Example usage:
items.RemoveWhere(item => item.IsWrong, removedItem =>
errorLog.AppendLine($"{removedItem} was wrong."));