在foreach循环中删除列表中的项目C#
问题描述:
如果我在foreach循环中使用了某个项目,但无法使用该项目,则必须删除当前在foreach循环中的该项目.
If I use an item in a foreach loop and I can't use the item it has to delete the item that is currently in the foreach loop.
这是我现在拥有的代码:
This is the code that I have right now:
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
}
}
感谢您有兴趣帮助其他人:)
Thanks for your interest to help other people :)
答
尝试为需要删除的项目创建另一个临时列表,然后在完成循环后,只需删除临时列表中的项目即可.
Try just creating another temporary list for the items that need to be deleted then when your done looping you can just delete the ones in the temp list.
List<Type> temp = new List<Type>()
foreach(item in mainList)
{
if (item.Delete)
{
temp.Add(item);
}
}
foreach (var item in temp)
{
mainList.Remove(item);
}