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

前端 未结 27 2419
忘了有多久
忘了有多久 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 23:35

    I found myself in a similar situation where I had to remove every nth element in a given List.

    for (int i = 0, j = 0, n = 3; i < list.Count; i++)
    {
        if ((j + 1) % n == 0) //Check current iteration is at the nth interval
        {
            list.RemoveAt(i);
            j++; //This extra addition is necessary. Without it j will wrap
                 //down to zero, which will throw off our index.
        }
        j++; //This will always advance the j counter
    }
    

提交回复
热议问题