2016-08-03 125 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

相關問題