Advertisement
SteelGolem

removing from list direction comparison

Aug 27th, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.72 KB | None | 0 0
  1. // make a list of strings
  2. List<string> myList = new List<string>();
  3.  
  4. // *** assume we added some strings to myList ***
  5.  
  6. // two ways we can look for the string "tourak" and remove it forever
  7.  
  8. // forwards
  9. for (int i = 0; i < myList.Count; i++)
  10. {
  11.     if (myList[i] == "tourak")
  12.     {
  13.         myList.RemoveAt(i);
  14.         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
  15.     }
  16. }
  17.  
  18. // backwards
  19. for (int i = myList.Count - 1; i >= 0; i--)
  20. {
  21.     if (myList[i] == "tourak")
  22.         myList.RemoveAt(i);
  23.     // no need to do anything more than this, easier and less thinking!
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement