Remove an item in a list while it's in a foreach loop c# [duplicate]

半世苍凉 提交于 2020-04-13 06:10:49

问题


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 :)


回答1:


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);
}



回答2:


You canNOT change the listing through which you are going. It is locked because it is an Enumeration as long as it is in the foreach. So use a for-loop instead.

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


来源:https://stackoverflow.com/questions/32503623/remove-an-item-in-a-list-while-its-in-a-foreach-loop-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!