Problems removing elements from a list when iterating through the list

When using List<T> the ToArray() method helps in this scenario vastly:

List<MyClass> items = new List<MyClass>();
foreach (MyClass item in items.ToArray())
{
    if (/* condition */) items.Remove(item);
}

The alternative is to use a for loop instead of a foreach, but then you have to decrement the index variable whenever you remove an element i.e.

List<MyClass> items = new List<MyClass>();
for (int i = 0; i < items.Count; i++)
{
    if (/* condition */)
    {
        items.RemoveAt(i);
        i--;
    }
}

If your list is an actual List<T> then you can use the built-in RemoveAll method to delete items based on a predicate:

int numberOfItemsRemoved = yourList.RemoveAll(x => ShouldThisItemBeDeleted(x));

You could use LINQ to replace the initial list by a new list by filtering out items:

IEnumerable<Foo> initialList = FetchList();
initialList = initialList.Where(x => SomeFilteringConditionOnElement(x));
// Now initialList will be filtered according to the condition
// The filtered elements will be subject to garbage collection

This way you don't have to worry about loops.

Tags:

C#

Loops

Foreach