1

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;
     }
 }
wonea
  • 4,425
  • 17
  • 82
  • 137
Zain Ali
  • 14,987
  • 14
  • 93
  • 106
  • possible duplicate of [How to modify or delete items from an enumerable collection while iterating through it in C#](http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-throu) – Alastair Pitts Aug 15 '11 at 06:43

4 Answers4

10
mainList.RemoveAll(x => x.Dead);
Cheng Chen
  • 41,149
  • 16
  • 109
  • 168
4

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);
    }
}
David Grayson
  • 79,096
  • 23
  • 144
  • 182
0

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();
Tomas Jansson
  • 21,761
  • 10
  • 75
  • 128
  • this doesn't remove the elements, though, it would require a further step to remove all the items in newList from mainList... – shelleybutterfly Aug 15 '11 at 06:46
  • no, it doesn't remove the item it creates a new list. The accepted solution does the samething behind the scene but with a delayed execution. – Tomas Jansson Aug 15 '11 at 08:11
  • well, it looks like the accepted solution is iterating backward through the list, and using RemoveAt(i) to remove the items, so I'm not sure I understand what you mean. (unless you mean the other proposed possible solution which was incomplete and commented on as a bad idea.) regardless, no offense was intended, I was just pointing out that your response does not answer the question, figuring you had forgotten to include the final step. – shelleybutterfly Aug 15 '11 at 08:31