0
for (int j = 0; j < list.Count; ++j )
{
     if (list[j].current_status == false)
     {  
       list.RemoveAt(j);  
     }  
}

I want to remove all the items which has current_status == false in the list, However, When execute the statement: list.RemoveAt(j), the list.Count will minus one. Finally, the original loop can not be looped from list[0] to list[list.Count]. How can I deal with this situation?

Thanks

Chester
  • 21
  • 1

3 Answers3

6

You could use RemoveAll instead of RemoveAt:

list.RemoveAll(item => item.current_status == false);
Jon
  • 16,212
  • 8
  • 50
  • 62
0
int size = list.Count;
for (int j = 0; j < size; ++j )
{
   if (list[j].current_status == false)
   {  
      list.RemoveAt(j);  
      size--;
      j--;
   }  
}
LVBen
  • 2,041
  • 13
  • 27
0

Also running linear time, a reverse loop like so:

for (int j = length - 1; j >= 0; j--)
{
    if (!list[j].current_status)
    {  
        list.RemoveAt(j);
    }
}

Side note : try not to test booleans with "==" and/or "!=" but use the expression itself or the negation symbol is needed

Philippe Paré
  • 4,279
  • 5
  • 36
  • 56