Monday, August 20, 2018

object emptied in foreach loop [duplicate]

This question already has an answer here:

I have a list being passed into a foreach loop which removes 0 or more items from the list. Based on conditions it is possible for the list to be entirely emptied which causes a null reference error. What is the best way to handle this sort of situation?

foreach (Item i in items)
{
    if (i.property == condition)
    {
        items.Remove(i);
    }
}

Solved

Use List.RemoveAll method

items.RemoveAll(i => i.property == condition)

It removes all the elements that match the conditions defined by the specified predicate.

You also can leave original list (or another collection) untouched by creating new list without items which match condition (sometimes that might be useful)

var newItems = items.Where(i => i.property != condition).ToList();

No comments:

Post a Comment