开发者

Safely remove list from list in loop

I am iterating through all the list in mainlist and if a specific condition occur. I want to remove that specific list.

It is not working.开发者_开发问答

for (int i = 0; i < mainList.Count; i++)
{
     if (mainList[i].Dead == true) //
     {
          mainList.removeAt(i);//what will be affect on mainList.Count;
     }
 }


mainList.RemoveAll(x => x.Dead);


The way you constructed your for loop, it will only work if mainList.Count stays constant, but you are removing elements during your loop. Do you understand why that is a problem? Whenever you remove an element you end up skipping the check of the element after it.

I think you could use foreach and mainList.remove but I'm not sure. Another solution is to just make your loop count downwards:

for (int i = mainList.Count-1; i >= 0; i--)
{
    if (mainList[i].Dead == true)
    {
         mainList.removeAt(i);
    }
}


You will not be able to do that since you are altering the length of the list when you are doing so. I would do it like this instead:

var newList = mainList.Where(y => !y.Dead).ToList();


How to modify or delete items from an enumerable collection while iterating through it in C#

http://bytes.com/topic/c-sharp/answers/238241-how-do-you-modify-array-while-iterating-through

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜