I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from
For loops are a bad construct for this.
while
var numbers = new List(Enumerable.Range(1, 3));
while (numbers.Count > 0)
{
numbers.RemoveAt(0);
}
But, if you absolutely must use for
var numbers = new List(Enumerable.Range(1, 3));
for (; numbers.Count > 0;)
{
numbers.RemoveAt(0);
}
Or, this:
public static class Extensions
{
public static IList Remove(
this IList numbers,
Func predicate)
{
numbers.ForEachBackwards(predicate, (n, index) => numbers.RemoveAt(index));
return numbers;
}
public static void ForEachBackwards(
this IList numbers,
Func predicate,
Action action)
{
for (var i = numbers.Count - 1; i >= 0; i--)
{
if (predicate(numbers[i]))
{
action(numbers[i], i);
}
}
}
}
Usage:
var numbers = new List(Enumerable.Range(1, 10)).Remove((n) => n > 5);