How to remove elements from a generic list while iterating over it?

前端 未结 27 2378
忘了有多久
忘了有多久 2020-11-21 22:48

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

27条回答
  •  长发绾君心
    2020-11-21 23:34

    For loops are a bad construct for this.

    Using 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);
    

提交回复
热议问题