我在迭代以下循环时收到InvalidOperationException
。为什么此代码在循环列表时抛出'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
元件。这两个列表都包含否无效或空元素。
其中一个列表中的元素看起来像在列表如下:{(LETTER:R, POSITION:(X:1Y:2))}
这里是我使用列表中的类...
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;
}
为什么我收到这个错误?
编辑: 我收到该错误消息是..
类型的未处理的异常 'System.InvalidOperationException' 出现在mscorlib.dll
其他信息:集合已修改;枚举操作 可能不会执行。
你的意思是这个异常消息,它告诉你*特别说明你在迭代时不允许修改集合吗? (不是我们“知道”这个,因为你没有在问题中包含错误的文本) –
虽然链接的答案解释了如何使用for循环来做,但是你也可以使用List.RemoveAll(Predicate)'删除项目。如果它不是列表,但实现了'IList ',则使用for循环并向后迭代(从最后一个元素开始)。 –
Groo