locked
best way with a foreach loop? RRS feed

  • Question

  • I have a foreach loop populated with 1000-3000+ custom items. What is the best way to remove majority of the items. Right now I copy all the ones I want to remove to a seperate arraylist and then when done loop through the second array and remove all of the values in the second array and all of the corresponding ones in the first. My current method locks up my application when running it. How can I stop it from locking up. Is there a more efficient and faster way to do it?
    Friday, August 21, 2009 2:36 AM

Answers

  • Not sure I get why you use a 2nd list.  However, right now your algorithm is at least O(n^2).  If you instead make a new list with the items you don't want to remove, you'll have a O(n) algorithm. 

    Hans Passant.
    • Proposed as answer by Louis.fr Friday, August 21, 2009 8:03 AM
    • Marked as answer by Figo Fei Wednesday, August 26, 2009 10:25 AM
    Friday, August 21, 2009 3:19 AM
    Moderator

All replies

  • Use a reverse while loop to remove items, that way you can do it in a single step.
    http://blog.voidnish.com
    Friday, August 21, 2009 2:46 AM
    Moderator
  • Not sure I get why you use a 2nd list.  However, right now your algorithm is at least O(n^2).  If you instead make a new list with the items you don't want to remove, you'll have a O(n) algorithm. 

    Hans Passant.
    • Proposed as answer by Louis.fr Friday, August 21, 2009 8:03 AM
    • Marked as answer by Figo Fei Wednesday, August 26, 2009 10:25 AM
    Friday, August 21, 2009 3:19 AM
    Moderator