2015-09-10 73 views
2

如果我在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 
    } 
} 

感謝您的關注,以幫助其他人:)

+0

這種捕獲看起來不錯。如果異常是由編碼錯誤引起的,例如'NullReferenceException'?你會默默地從數組中刪除該行? –

+0

我剛剛得到了正確的答案:.ToList() 找不到更好的答案,但現在我發現它已被刪除。 –

回答

1

嘗試爲需要刪除的項目創建另一個臨時列表,然後當完成循環時,您可以刪除臨時列表中的項目。

List<Type> temp = new List<Type>() 
foreach(item in mainList) 
{ 
    if (item.Delete) 
    { 
     temp.Add(item); 
    } 
} 

foreach (var item in temp) 
{ 
    mainList.Remove(item); 
} 
2

你不能改變你通過它去上市。 它被鎖定,因爲只要它在foreach中就是一個Enumeration。 因此,使用for-loop代替。

for (int i = 0; i < linelijst.count; i++) 
{ 
    // linelijst[i] can be changed. 
} 
+2

應該注意的是,當物品被移除時,你會想從索引中減去一個,所以你不會跳過任何東西,或者如果可能的話,從列表的末尾迭代。 – juharr