如果我在foreach循環中使用某個項目,並且無法使用該項目,則必須刪除當前處於foreach循環中的項目。在foreach循環中刪除列表中的項目c#
這是我現在所擁有的代碼:
foreach (Line line in linelijst)
{
try
{
if (line.ActorIndex() == 0)
{
line.setStartPoint(actorenlijst[0].getLinePoint()); //if actorenlijst[0] doesn't excist it has to delete the current line
}
if (line.ActorIndex() == 1)
{
line.setStartPoint(actorenlijst[1].getLinePoint()); //if actorenlijst[1] doesn't excist it has to delete the current line
}
if (line.ActorIndex() == 2)
{
line.setStartPoint(actorenlijst[2].getLinePoint()); //if actorenlijst[2] doesn't excist it has to delete the current line
}
Point start = line.getStartPoint();
Point end = line.getEndPoint();
Pen lijn = new Pen(Color.Black, 1);
graphics.DrawLine(lijn, start, end);
}
catch
{
//delete current line from the list
}
}
感謝您的關注,以幫助其他人:)
這種捕獲看起來不錯。如果異常是由編碼錯誤引起的,例如'NullReferenceException'?你會默默地從數組中刪除該行? –
我剛剛得到了正確的答案:.ToList() 找不到更好的答案,但現在我發現它已被刪除。 –