code_junkie

How to remove objects from an Enumerable collection in a loop

Nov 13th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. foreach (MyObject myObject in MyListOfMyObjects)
  2. {
  3. if (condition) MyListOfMyObjects.Remove(myObject);
  4. }
  5.  
  6. foreach (MyObject myObject in new List<MyObject>(MyListOfMyObjects))
  7. {
  8. if (condition) MyListOfMyObjects.Remove(myObject);
  9. }
  10.  
  11. List myFilteredList = new List();
  12. foreach (MyObject myObject in myListOfMyObjects)
  13. {
  14. if (!condition) myFilteredList.Add(myObject);
  15. }
  16.  
  17. var myFilteredList = from myObject in myListOfMyObjects
  18. where !condition
  19. select myObject;
  20.  
  21. void RemoveAll(object condition)
  22. {
  23.  
  24. bool found = false;
  25.  
  26. foreach(object thisObject in objects)
  27. {
  28.  
  29. if (condition)
  30. {
  31. objects.Remove(thisObject);
  32.  
  33. found = true;
  34.  
  35. break; //exit loop
  36. }
  37. }
  38.  
  39. // Call again recursively
  40.  
  41. if (found) RemoveAll(condition);
  42.  
  43. }
Add Comment
Please, Sign In to add comment