On Joining TObjectlists
Asked Answered
R

2

5

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?

Roryros answered 17/5, 2010 at 9:23 Comment(0)
C
12

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;
Clothe answered 17/5, 2010 at 10:13 Comment(2)
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...Bunt
Well, the OP's using a generic TObjectList in his example, so he should be fine.Eternize
M
0

Alas, the answer supplied looks like it only works in XE.. in 2010 (and presumably below) the AddRange function does not have an overload that takes a TObjectList as its parameter (compiling the above code snippet gives an E2250 on the AddRange lines).

Currently spending a day working if generics will help simplify code in a large project but the lack of an assign function (or any usable equivalent) is a showstopper. Seems odd to release something in D2009 then require 2 major releases before it actually works!

Melanism answered 15/12, 2010 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.