Beny
Beny

Reputation: 900

How can I quickly remove duplicates from a list box?

I wish to remove duplicate items from a large TListBox. To do that I use a classic simple method. It works, but it takes 19 minutes. I read a lot and apparently I should use a TFileStream (?). But I don't know how.

My classic method is this:

procedure NoDup(AListBox : TListBox);
var
  i : integer;
begin
  with AListBox do
  for i := Items.Count - 1 downto 0 do
  begin
    if Items.IndexOf(Items[i]) < i then
    Items.Delete(i);
    Application.ProcessMessages;
  end;
end;

How can I improve the speed?

Upvotes: 6

Views: 4175

Answers (1)

user219760
user219760

Reputation:

procedure NoDup(AListBox: TListBox);
var
  lStringList: TStringList;
begin
  lStringList := TStringList.Create;
  try
    lStringList.Duplicates := dupIgnore;
    lStringList.Sorted := true;
    lStringList.Assign(AListBox.Items);
    AListBox.Items.Assign(lStringList);
  finally
    lStringList.free
  end;
end;

Upvotes: 11

Related Questions