Entwickler-Ecke

Delphi Language (Object-Pascal) / CLX - How to selectively delete from TList


invarbrass - Di 29.04.08 06:47
Titel: How to selectively delete from TList
I have a snippet of code that iterates through a TList and deletes some items. The code is as follows:

Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
procedure PurgeList;
var
  P: PSomeRecord;
  I: Integer;
begin
  I := 0;
  while (I < FList.Count) do  
  begin
    P := PSomeRecord(FList[I]);
    if P^.CanDelete then
    begin
      FreeMem(P);
      P := nil;
      FList.Delete(I);
      Continue;
    end;
    Inc(I);
  end;
end;

Is this the right way to delete items from a tlist? or will it enter into an infinite loop?
can anyone show me any other way to remove items from a tlist?
thanks in advance


hazard999 - Di 29.04.08 07:22

Hi,

your source isn't wrong at all.

But you've to count downto 0.

If you're counting upwards you will leave every item after a delete untouched.

r u

René


Narses - Di 29.04.08 07:24
Titel: Re: How to selectively delete from TList
Hi!

I would suggest this:

Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
procedure PurgeList;
  var
    P: PSomeRecord;
    i: Integer;
begin
  for i := FList.Count-1 downto 0 do begin
    P := PSomeRecord(FList.Items[i]);
    if (P^.CanDelete) then begin
      FreeMem(P);
      FList.Delete(i);
    end;
  end;
end;
cu
Narses


invarbrass - Di 29.04.08 17:17

thanks for the ideas. much appreciated. i've updated my code according to your suggestions. :D