using System.Collections.Generic;
using System.Runtime.InteropServices;
public static class Program
public static void Main()
List<int> list = new(Enumerable.Range(1, 15));
Console.WriteLine($"Before RemoveAll: [{String.Join(", ", list)}]");
list.RemoveAll((item, index) =>
if (item == 10) throw new Exception();
bool removeIt = item % 2 == 1;
if (removeIt) Console.WriteLine($"Removing #{item}");
catch (Exception ex) { Console.WriteLine(ex); }
Console.WriteLine($"After RemoveAll: [{String.Join(", ", list)}]");
public static int RemoveAll<T>(this List<T> list, Func<T, int, bool> predicate)
ArgumentNullException.ThrowIfNull(list);
ArgumentNullException.ThrowIfNull(predicate);
Span<T> span = CollectionsMarshal.AsSpan(list);
for (; i < span.Length; i++)
if (predicate(span[i], i)) continue;
if (j < i) span[j] = span[i];
for (; i < span.Length; i++, j++)
list.RemoveRange(j, span.Length - j);