在foreach循环中删除列表中的项目c#

问题描述:

如果我在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() 找不到更好的答案,但现在我发现它已被删除。 –

尝试为需要删除的项目创建另一个临时列表,然后当完成循环时,您可以删除临时列表中的项目。

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

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

你不能改变你通过它去上市。 它被锁定,因为只要它在foreach中就是一个Enumeration。 因此,使用for-loop代替。

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

应该注意的是,当物品被移除时,你会想从索引中减去一个,所以你不会跳过任何东西,或者如果可能的话,从列表的末尾迭代。 – juharr