Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Delphi
How do you add or combine two TStringList objects to eachother? eg.
 
var
  List1, List2, List3 : TStringList;
begin
  List1.Add('Line1List1');
  List1.Add('Line2List1');
  List2.Add('Line1List2');
  List2.Add('Line2List2');
end
 
are the two lists with respective strings. How do I combine them into a single list?
Like List3 having:
'Line1List1'
'Line2List1'
'Line1List2'
'Line2List2'
which is (List1 + List2).
 
How can I do this? No help found...
Posted 30-Jun-12 5:27am
Comments
Sergey Alexandrovich Kryukov at 1-Jul-12 3:50am
   
Is this +, or disjunction?
Damith is right, that's why the like with IndexOf -- it exclude duplicates, but this check can be optional, to make just '+'.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

procedure MergeStrings(Dest, Source: TStrings) ;
var j : integer;
begin
   for j := 0 to -1 + Source.Count do
     if Dest.IndexOf(Source[j]) = -1 then
       Dest.Add(Source[j]) ;
end;
 
http://delphi.about.com/cs/adptips2003/a/bltip0703_4.htm[^]
  Permalink  
v2
Comments
Sergey Alexandrovich Kryukov at 1-Jul-12 3:48am
   
Right, a 5.
--SA
Sergey Alexandrovich Kryukov at 1-Jul-12 3:51am
   
The check ("IndexOf") could be optional...
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

You can set the Duplicate method of TStringList object with dupIgnore :
 
procedure CombineStrings(S1, S2, CombinedList: TStringList);
begin
  S1.Duplicates := dupIgnore;
  S1.Sorted := True;
  S1.AddStrings(S2);
  CombinedList := S1;
end;
 
Sample :
 
var
  SList1, SList2: TStringList;
begin
  SList1 := TStringList.Create;
  SList2 := TStringList.Create;
  try
    SList1.Add('Item 1');
    SList1.Add('Item 2');
    SList2.Add('Item 1');
    SList2.Add('Item 2');
    SList2.Add('Item 3');
 
    CombineStrings(SList1, SList2, SList1);
 
    ListBox1.Items.Assign(SList1);
  finally
    SList1.Free;
    SList2.Free;
  end;
end;
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 325
1 Sergey Alexandrovich Kryukov 289
2 CPallini 275
3 DamithSL 260
4 Maciej Los 215
0 OriginalGriff 5,455
1 DamithSL 4,422
2 Maciej Los 3,860
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,010


Advertise | Privacy | Mobile
Web02 | 2.8.141216.1 | Last Updated 5 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100