SteelGolem icon

removing from list direction comparison

SteelGolem | PRO | 08/27/16 02:31:13 PM UTC | 0 ⭐ | 455 👁️ | Never ⏰ | []
C# |

720 B

|

None

|

0 👍

/

0 👎

// make a list of strings
List<string> myList = new List<string>();
 
// *** assume we added some strings to myList ***
 
// two ways we can look for the string "tourak" and remove it forever
 
// forwards
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i] == "tourak")
    {
        myList.RemoveAt(i);
        i--; // next loop, i will move ahead by 1, but we just removed the item already at i, so there's no need to move from this spot; moving back one will put us back here at the start of the next loop
    }
}
 
// backwards
for (int i = myList.Count - 1; i >= 0; i--)
{
    if (myList[i] == "tourak")
        myList.RemoveAt(i);
    // no need to do anything more than this, easier and less thinking!
}

Comments