Search code examples
delphigenericsdelphi-2010concatenationtobjectlist

On Joining TObjectlists


I think i need a nudge in the right direction:

I have two Tobjectlists of the same datatype, and i want to concatenate these into a new list into which list1 shall be copied (unmodified) followed by list2 (in reverse)

type
  TMyListType = TobjectList<MyClass>

var
  list1, list2, resList : TMyListtype

begin
  FillListWithObjects(list1);
  FillListWithOtherObjects(list2);

  list2.reverse

  //Now, I tried to use resList.Assign(list1, list2, laOr), 
  //but Tobjectlist has no Assign-Method. I would rather not want to 
  //iterate over all objects in my lists to fill the resList
end;

Does delphi have any built-in function to merge two Tobjectlists into one?


Solution

  • Use TObjectList.AddRange() and set OwnsObjects to False to avoid double-freeing of the items in LRes.

    var
      L1, L2, LRes: TObjectList<TPerson>;
      Item: TPerson;
    
    {...}
    
    L1 := TObjectList<TPerson>.Create();
    try
      L2 := TObjectList<TPerson>.Create();
      try
    
        LRes := TObjectList<TPerson>.Create();
        try
          L1.Add(TPerson.Create('aa', 'AA'));
          L1.Add(TPerson.Create('bb', 'BB'));
    
          L2.Add(TPerson.Create('xx', 'XX'));
          L2.Add(TPerson.Create('yy', 'YY'));
    
          L2.Reverse;
    
          LRes.OwnsObjects := False;
          LRes.AddRange(L1);
          LRes.AddRange(L2);
    
          for Item in LRes do
          begin
            OutputWriteLine(Item.FirstName + ' ' + Item.LastName);
          end;
    
        finally
          LRes.Free;
        end;
    
      finally
        L2.Free;
      end;
    
    finally
      L1.Free;
    end;