-2

I'm programming in c#. I'm trying to remove an item from a List<> but when I remove the item I get this exception error:

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code

Additional information: Collection was modified; enumeration operation may not execute.

Here is my code:

foreach (Target t in targetList)
{
    if (t.CalculateDistance(t.EndX, t.EndY) <= 5)
    {
        targetList.Remove(t);
    }
}

I get exception on first line. Why do I see this error? or How can I fix it?

Saagar Elias Jacky
  • 2,684
  • 2
  • 14
  • 28
Babak.Abad
  • 2,839
  • 10
  • 40
  • 74
  • 1
    you can't modify while enumerating. do a for loop instead. – Dom Apr 24 '15 at 20:33
  • You can either: use a `for` loop, which I don't recommend, your `iterator` will likely end up out-of-range at some point; create a second `List` or `Array` to hold values you wish to remove, then add each value you wish to remove to the `List` or `Array` and after complete, iterate through that `List` or `Array` and remove those from the original `List` or `Array`. – Der Kommissar Apr 24 '15 at 20:35
  • 2
    `Your iterator will likely end up out-of-range at some point` not if you go backwards – Ňɏssa Pøngjǣrdenlarp Apr 24 '15 at 20:36
  • @Plutonix That is true, though not recommended. As I said, *likely*. OP should refer to the LINQ query in the first answer here. – Der Kommissar Apr 24 '15 at 20:39
  • this is one reason why I hardly ever use foreach . LOL – RadioSpace Apr 24 '15 at 20:51

2 Answers2

12

The problem you face is that you can't modify the collection you itterate thru. You could solve this by using linq:

targetList.RemoveAll(t => t.CalculateDistance(t.EndX, t.EndY) <= 5);
Luc
  • 1,491
  • 1
  • 12
  • 21
  • Valid answer, but it would be helpful if you described WHY the OP's solution wasn't working. That was the first part to his question. – Rufus L Apr 24 '15 at 20:49
1

Try this:

var needdelete = new List<Target>();

foreach (Target t in targetList)
{
    if (t.CalculateDistance(t.EndX, t.EndY) <= 5)
    {
        needdelete.Add(t);           
    }
}

targetlist.RemoveRange(needdelete);
Rufus L
  • 36,127
  • 5
  • 30
  • 43