Removing duplicate items from ListBox in Delphi

How can I remove duplicate items from ListBox in Delphi? I know this:

for i := ListBox1.Items.Count-1 downto 1 do
     for j := 0 to i-1 do
       if ListBox1.Items[i] = ListBox1.Items[j] then
         ListBox1.Items.Delete[i]; 

But I need to remove duplicates only if first 10 letters are the same, so I have tried this:

for i := ListBox1.Items.Count-1 downto 1 do
         for j := 0 to i-1 do
           if copy(ListBox1.Items[i],1,11) = copy(ListBox1.Items[j],1,11) then
             ListBox1.Items.Delete[i]; 

But when I try to remove duplicates, I get list out of bonds error :(

Upvotes: 1

Views: 4051

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138970

If you don't mind sorting the items in ListBox1 you can delete the duplicates in one pass.

var
  s: string;
  I: Integer;
begin
  ListBox1.Sorted := True;
  s := '';
  I := 0;
  while I < ListBox1.Count do
  begin
    if s = copy(ListBox1.Items[I], 1, 10) then
    begin
      ListBox1.Items.Delete(I);
    end
    else
    begin
      s := copy(ListBox1.Items[I], 1, 10);
      Inc(I);
    end;
  end;
end;

Upvotes: 4

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108948

You need to add a break after the Delete:

if Copy(ListBox1.Items[i], 1, 10) = Copy(ListBox1.Items[j], 1, 10) then
begin
  ListBox1.Items.Delete(i); 
  break;
end;

(Indeed, if you Delete the item with index i, then how can you make the comparison if Copy(ListBox1.Items[i], 1, 10) = ... the next time?)

Upvotes: 10

Related Questions