Forum > General

TStringList Super-Mega Bug

(1/1)

anna:
First, start new Application on Lazarus. Add TMemo and TButton components. For Button1 handler write next:

--- Code: ---procedure TForm1.Button1Click(Sender: TObject);
var L : TStringList;
begin
  L := TStringList.Create;
  L.Duplicates:=dupIgnore;
  L.Text:=Memo1.Text
  Memo1.Text:=L.Text;
  L.Free;
end;  
--- End code ---

Run project. Then write into Memo1's field next:
4
3
2
1
2
3
4
Press Button1. And you will see old
4
3
2
1
2
3
4
instead of
4
3
2
1


Why? Extremely stupid, huh?

theo:

--- Quote from: anna on August 05, 2010, 05:01:40 pm ---Extremely stupid, huh?

--- End quote ---

Yes ;-)

This only works if the StringList ist sorted. This is documented:
http://www.freepascal.org/docs-html/rtl/classes/tstringlist.duplicates.html

anna:

--- Quote from: theo on August 05, 2010, 05:19:28 pm ---
--- Quote from: anna on August 05, 2010, 05:01:40 pm ---Extremely stupid, huh?

--- End quote ---

Yes ;-)

This only works if the StringList ist sorted. This is documented:
http://www.freepascal.org/docs-html/rtl/classes/tstringlist.duplicates.html

--- End quote ---
M-m-m-m...  :'(
But what should I do if i don't need sort?

eny:

--- Quote from: anna on August 05, 2010, 05:31:29 pm ---But what should I do if i don't need sort?

--- End quote ---
It depends on your needs:
1. you don't need it, but it doesn't bother your: accept the sorted list as is.
2. you want to rely on the insertion order, without having duplicates: you'll need to create a workaround.

With hindsight: sorted and duplicates are mutually exclusive. It would be better to have 1 state that describes the handling of insertions. Something like

--- Code: ---TSortState = (ssUnsorted, ssDuplicatesIgnore, ssNoDuplicatesAccept, ssDuplicatesError);

--- End code ---

theo:

--- Quote from: anna on August 05, 2010, 05:31:29 pm ---But what should I do if i don't need sort?

--- End quote ---

It's not that hard.
something like this (just written down now, not tested):


--- Code: ---For i:=0 to Memo1.Lines.Count-1 do
if SL.IndexOf(Memo1.Lines[i])<0 then SL.Add(Memo1.Lines[i]);
--- End code ---

Navigation

[0] Message Index

Go to full version