Efficiently deleting item from within 'foreach'

后端 未结 5 1222
别跟我提以往
别跟我提以往 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:33

    The lambda way is good. You could also use a regular for loop, you can iterate lists that a for loop uses within the loop itself, unlike a foreach loop.

    for (int i = collection.Count-1; i >= 0; i--)
    {
        if(ShouldBeDeleted(collection[i])
            collection.RemoveAt(i);
    }
    

    I am assuming that collection is an arraylist here, the code might be a bit different if you are using a different data structure.

提交回复
热议问题