Efficiently deleting item from within 'foreach'

后端 未结 5 1224
别跟我提以往
别跟我提以往 2020-12-05 20:00

For now, the best I could think of is:

bool oneMoreTime = true;
while (oneMoreTime)
{
    ItemType toDelete=null;
    oneMoreTime=false;
    foreach (ItemTyp         


        
5条回答
  •  北海茫月
    2020-12-05 20:29

    A forward variation on the backward for loop:

    for (int i = 0; i < collection.Count; )
        if (ShouldBeDeleted(collection[i]))
            collection.RemoveAt(i)
        else
            i++;
    

提交回复
热议问题