Collection was modified; enumeration operation may not execute

Ever tried to remove or change something in a C# Enumeration while you iterate over it? Yes, it does not work very well.

But there are ways around it.

foreach (Item item in items.ToArray())
    if (item.Visible == false)

The simplest way is to use ToArray(). No much coding, no complicated loops, but obviously not very efficient for larger lists.

A few alternatives are presented by Kevin Ransom.

Ähnliche Beiträge

3 Kommentare zu “Collection was modified; enumeration operation may not execute”

  • Paul am 22. April 2010 9:34 am Uhr

    Simple, but effective! Exactly what I needed.

  • Megan Ward am 23. April 2010 4:31 am Uhr

    Ha, did a double loop last time. Silly me 🙂

  • Mister Follow am 23. April 2010 4:33 am Uhr

    Yep, good idea indeed.

Leave a Reply

Your email address will not be published. Required fields are marked *