Delete rows from TStringList

I have a list box or list view with items. And I have a String List with the same elements (strings) as the List List / List View. I want to remove all selected items in the List / List view from a list of strings.

How to make?

for i:=0 to ListBox.Count-1 do
  if ListBox.Selected[i] then
    StringList1.Delete(i); // I cannot know exactly an index, other strings move up
+5
source share
4 answers
for i := ListBox.Count - 1 downto 0 do
  if ListBox.Selected[i] then
    StringList1.Delete(i);
+19
source

The trick is to start the loop in the reverse order:

for i := ListBox.Count-1 downto 0 do
  if ListBox.Selected[i] then 
    StringList1.Delete(i);

Thus, the action of deleting an element only changes the indices of the elements later in the list, and these elements are already processed.

+15
source

, , , ListBox, StringList. , , , , StringList IndexOf ( StringList , Find). -

var x, Idx: Integer;
for x := ListBox.Count - 1 downto 0 do begin
   if ListBox.Selected[x] then begin
      idx := StringList.IndexOf(ListBox.Items[x]);
      if(idx <> -1)then StringList.Delete(idx);
   end;
end;
+9
source

How to do it in another way (adding instead of deleting)?

StringList1.Clear;
for i:=0 to ListBox.Count-1 do
  if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
+4
source

All Articles