我一直在寻找同样的东西。我想对要删除的项目进行一些错误记录。由于我添加了一大堆验证规则,remove-and-log 调用应该尽可能简洁。
我做了以下扩展方法:
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);
}
}
示例用法:
items.RemoveWhere(item => item.IsWrong, removedItem =>
errorLog.AppendLine($"{removedItem} was wrong."));