2016-08-03 128 views
0

我在迭代以下循环时收到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

其他信息:集合已修改;枚举操作 可能不会执行。

+1

你的意思是这个异常消息,它告诉你*特别说明你在迭代时不允许修改集合吗? (不是我们“知道”这个,因为你没有在问题中包含错误的文本) –

+0

虽然链接的答案解释了如何使用for循环来做,但是你也可以使用List.RemoveAll(Predicate )'删除项目。如果它不是列表,但实现了'IList ',则使用for循环并向后迭代(从最后一个元素开始)。 – Groo

回答

1

因为在每个操作过程中,您不能修改(删除或添加元素)到列表中,请尝试使用for循环。

+0

需要注意的是'for'循环必须在** reverse **中迭代才能正常工作(或者每次删除操作时必须减少索引)。 – Groo

相关问题