views:

114

answers:

1

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 used unmodified followed by list2 reversed)

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?

+9  A: 

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;
ulrichb
Note that AddRange is available only on the generic version of TObjectList, so it did not exist in 2006 (and probably 2007). Should be ok if you use a recent version. Otherwise you have to make this add-all loop. It is simple enough...
deepc
Well, the OP's using a generic TObjectList in his example, so he should be fine.
Mason Wheeler
Thanks, that solves my problems!
sum1stolemyname