Recent

Author Topic: TStringList Super-Mega Bug  (Read 5967 times)

anna

  • Sr. Member
  • ****
  • Posts: 426
TStringList Super-Mega Bug
« on: August 05, 2010, 05:01:40 pm »
First, start new Application on Lazarus. Add TMemo and TButton components. For Button1 handler write next:
Code: [Select]
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;  

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?
« Last Edit: August 05, 2010, 05:14:31 pm by anna »
WinXP SP3 Pro Russian 32-bit (5.1.2600)

theo

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1927
Re: TStringList Super-Mega Bug
« Reply #1 on: August 05, 2010, 05:19:28 pm »
Extremely stupid, huh?

Yes ;-)

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

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: TStringList Super-Mega Bug
« Reply #2 on: August 05, 2010, 05:31:29 pm »
Extremely stupid, huh?

Yes ;-)

This only works if the StringList ist sorted. This is documented:
http://www.freepascal.org/docs-html/rtl/classes/tstringlist.duplicates.html
M-m-m-m...  :'(
But what should I do if i don't need sort?
WinXP SP3 Pro Russian 32-bit (5.1.2600)

eny

  • Hero Member
  • *****
  • Posts: 1634
Re: TStringList Super-Mega Bug
« Reply #3 on: August 05, 2010, 05:38:14 pm »
But what should I do if i don't need sort?
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: [Select]
TSortState = (ssUnsorted, ssDuplicatesIgnore, ssNoDuplicatesAccept, ssDuplicatesError);
« Last Edit: August 05, 2010, 05:42:51 pm by eny »
All posts based on: Win10 (Win64); Lazarus 2.0.10 'stable' (x64) unless specified otherwise...

theo

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1927
Re: TStringList Super-Mega Bug
« Reply #4 on: August 05, 2010, 05:58:49 pm »
But what should I do if i don't need sort?

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

Code: [Select]
For i:=0 to Memo1.Lines.Count-1 do
if SL.IndexOf(Memo1.Lines[i])<0 then SL.Add(Memo1.Lines[i]);
« Last Edit: August 05, 2010, 06:04:38 pm by theo »

 

TinyPortal © 2005-2018