0

I'm receiving an InvalidOperationException when iterating over the following loop.

foreach (LetterPoint word in NonIntersectingWordsLocations) {
        if (IntersectingWordsLocations.Any(item => item.Position.X == word.Position.X && item.Position.Y == word.Position.Y && item.Letter == word.Letter)) {
            NonIntersectingWordsLocations.Remove(word);
        }
    }

At that point in the code, IntersectingWordsLocations contains a total of 12 elements and NonIntersectingWordLocations contains a total of 57 elements. Both lists contain NO invalid or null elements.

One of these list elements looks like the following in the list: {(LETTER:R, POSITION:(X:1Y:2))}

Here is the class I am using for the list...

LetterPoint.cs

public class LetterPoint : LetterData<Point>, IEquatable<LetterPoint> {
    public Point Position {
        get { return Item; }
        set { Item = value; }
    }
    public LetterPoint(char c = ' ', int row = 0, int col = 0) {
        Letter = c;
        Position = new Point(row, col);
    }
    public string PositionToString => $"(X:{Item.X}Y:{Item.Y})";
    public override string ToString() => $"(LETTER:{Letter}, POSITION:{PositionToString})";

    // TO USE THE .COMPARE FUNCTION IN THE MAIN FILE
    public bool Equals(LetterPoint other) => Letter == other.Letter && Position == other.Position;
}

Why am I recieving this error?

EDIT: The error message I am receiving is..

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

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

TheAuzzieJesus
  • 587
  • 9
  • 23
  • 1
    You mean the exception message that tells you *specifically* that you're not allowed to modify the collection while you're iterating through it? (Not that we "know" this since you didn't include the text of the error in the question) – Damien_The_Unbeliever Aug 03 '16 at 07:12
  • While the linked answer explains how to do it using a `for` loop, you might also use `List.RemoveAll(Predicate)` to remove the items. If it's not a list, but implements `IList`, then use a for loop and iterate backwards (from the last element). – vgru Aug 03 '16 at 07:15

1 Answers1

1

Because you can not modify(delete or add elements) to a list during a for each operation on it,try use for loop instead.

Dr.Haimovitz
  • 1,568
  • 12
  • 16
  • It's important to note that `for` loop must be iterated in **reverse** for this to work properly (or the index must be decreased on each remove operation). – vgru Aug 03 '16 at 07:17