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

前端 未结 27 2410
忘了有多久
忘了有多久 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:22

    Iterate your list in reverse with a for loop:

    for (int i = safePendingList.Count - 1; i >= 0; i--)
    {
        // some code
        // safePendingList.RemoveAt(i);
    }
    

    Example:

    var list = new List(Enumerable.Range(1, 10));
    for (int i = list.Count - 1; i >= 0; i--)
    {
        if (list[i] > 5)
            list.RemoveAt(i);
    }
    list.ForEach(i => Console.WriteLine(i));
    

    Alternately, you can use the RemoveAll method with a predicate to test against:

    safePendingList.RemoveAll(item => item.Value == someValue);
    

    Here's a simplified example to demonstrate:

    var list = new List(Enumerable.Range(1, 10));
    Console.WriteLine("Before:");
    list.ForEach(i => Console.WriteLine(i));
    list.RemoveAll(i => i > 5);
    Console.WriteLine("After:");
    list.ForEach(i => Console.WriteLine(i));
    

提交回复
热议问题