c# - correct way of looping trough a list and remove items -


i wrote function go trough list , remove list items if conditions met. program crashed on it, , after while concluded outer loop, goes through items in list. while @ same routine list of item can shorter.

 // lijst list of struct contains value .scanned , .price   (int = 0; < lijst.count; i++)   {    if (lijst[i].scanned == false)     {      // (removed deletion of list item here)      if (lijst[i].price > (int)nudminimum.value)       {        totaal++;         lbldebug.text = totaal.tostring();       }     lijst.removeat(i); //<-moved here     }    } 

now wonder whats correct this, without getting index out of range errors.

you might looking

for (int = lijst.count - 1 ; >= 0 ; i--) {     if (lijst[i].scanned == false)     {         if (lijst[i].price > (int)nudminimum.value)         {             totaal++;             lbldebug.text = totaal.tostring();         }         lijst.removeat(i);     } } 

question in comment:

why other direction loop work ?

because when loop run in 0 count there situation arise when index not available remove , count still left. example:

if have 10 items in list loop starts @ 0 , remove 0,1,2,3,4 , item left 5 , index 5 remove item too. after when loop value reaches 6 , item left 4. create problem. , throw error. i.e. index out of range


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -