Home > Mobile >  How to remove duplicate items in a ListView?
How to remove duplicate items in a ListView?

Time:12-30

I have a TListView with some items in it:

item1
item1
item2

I want to remove duplicate items when I click on a button:

item1
item2

Here is my code so far:

procedure TMainForm.Button3Click(Sender: TObject);
var i,j, k: integer;
begin
  I := 0;
  while I < ListView1.Items.Count  do
  begin
    for j := ListView1.Items.Count - 1 downto 0 do
    begin
      if ListView1.Items[I].SubItems[3] = ListView1.Items[j].SubItems[3] then
        ListView1.Items.Delete(J);
        Continue;
       end;
       Inc(I);
  end;
end;

It's deleting all items. How can I fix this?

CodePudding user response:

The items are not deleted immediately when you call Delete(). The ListView must return to the message loop for the items to actually become deleted. Therefore, if you have the same item on e.g. line 1 and line 4, both lines will deleted:

  • line 4 when i=1 and j=4
  • line 1 when i=4 and j=1

This is fixed by changing the for j := ... loop to:

for j := ListView1.Items.Count - 1 downto i 1 do // instead of downto 0

That ensures that a pair of line is compared only once, and that the latter of two equal lines is removed.

  • Related