Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
sum1stolemyname Avatar asked May 17 '10 09:05

sum1stolemyname


1 Answers

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;
like image 105
ulrichb Avatar answered Oct 11 '22 21:10

ulrichb