Mega Code Archive

 
Categories / Delphi / Examples
 

Deleting items from a list

Title: Deleting items from a list Question: How do I easily remove items from a list? Answer: Well, I wasn't sure if I should post that or not, it's really a simple trick, but new programmers will appreciate it. When you remove an item from a list, you change the Index of items after the one you delete. This causes problems because you cannot scan through the list like this: with Listbox1.Items do for i := 0 to Count - 1 do begin if Strings[i] = 'Deleteme' then Delete(i); end; While this might seems fine, it's not. When you delete item [i], item [i+1] takes it's place, but the loop continues, so you actually skip the "next" item. Also, in a FOR loop, the condition is not re-evaluated after each loop, so you end up accessing items past [Count - 1], and you get an EListError with Index Out Of Bounds. Instead of using a WHILE loop and a counter you manage by hand, just access the list in reverse order starting at the end: with Listbox1.Items do for i := Count - 1 downto 0 do begin if Strings[i] = 'Deleteme' then Delete(i); end; And that's all! No more out of bounds errors and no more skipped items.