为什么此代码在循环列表时抛出 'InvalidOperationException'?
Why is this code throwing an 'InvalidOperationException' when looping a list?
我在迭代以下循环时收到 InvalidOperationException
。
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);
}
}
在代码的那一点,IntersectingWordsLocations
总共包含 12
个元素,NonIntersectingWordLocations
总共包含 57
个元素。两个列表都包含 NO 个无效或空元素。
其中一个列表元素在列表中如下所示:{(LETTER:R, POSITION:(X:1Y:2))}
这是我用于列表的 class...
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;
}
为什么我会收到此错误消息?
编辑:
我收到的错误消息是..
An unhandled exception of type 'System.InvalidOperationException'
occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation
may not execute.
因为你不能在对它的每个操作期间修改(删除或添加元素)到列表,请尝试使用 for 循环。
我在迭代以下循环时收到 InvalidOperationException
。
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);
}
}
在代码的那一点,IntersectingWordsLocations
总共包含 12
个元素,NonIntersectingWordLocations
总共包含 57
个元素。两个列表都包含 NO 个无效或空元素。
其中一个列表元素在列表中如下所示:{(LETTER:R, POSITION:(X:1Y:2))}
这是我用于列表的 class...
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;
}
为什么我会收到此错误消息?
编辑: 我收到的错误消息是..
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation may not execute.
因为你不能在对它的每个操作期间修改(删除或添加元素)到列表,请尝试使用 for 循环。