Recent

Author Topic: Obtain a sublist from a TList  (Read 3482 times)

py2pa

  • New Member
  • *
  • Posts: 11
Obtain a sublist from a TList
« on: August 17, 2014, 07:18:40 pm »
Is there a convenience function to get a new sublist from a TList/TFPGList object? I'm looking for something similar to list slicing that Python does when I write:

Code: [Select]
new_sublist = source_list[from_element:to_element]
I searched the documentation but I couldn't find a TList method suitable for the task (Assign perhaps?). Do I have to copy the elements manually to the new list?

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Obtain a sublist from a TList
« Reply #1 on: August 17, 2014, 08:25:34 pm »
A simple-minded descendant of this sort should do it

Code: [Select]
uses Classes;

TSliceList = class(TList)
public
   function SliceList(startSlice, endSlice: integer): TList;
end;

implementation

function TSliceList.SliceList(startSlice, endSlice: integer): TList;
var
  j: integer;
begin
  Result:=nil;
  j:=Count;
  if (startSlice > -1) and (startSlice < j) and (endSlice > -1) and
    (endSlice < j) and (startSlice < endSlice) then
  begin
    Result:=TList.Create;
    j:=endSlice - startSlice + 1;
    Result.Capacity:=j;
    for j:=startSlice to endSlice do
      Result.Add(Items[j]);
  end;
end;

py2pa

  • New Member
  • *
  • Posts: 11
Re: Obtain a sublist from a TList
« Reply #2 on: August 17, 2014, 08:49:49 pm »
A simple-minded descendant of this sort should do it

Code: [Select]
uses Classes;

TSliceList = class(TList)
public
   function SliceList(startSlice, endSlice: integer): TList;
end;

implementation

function TSliceList.SliceList(startSlice, endSlice: integer): TList;
var
  j: integer;
begin
  Result:=nil;
  j:=Count;
  if (startSlice > -1) and (startSlice < j) and (endSlice > -1) and
    (endSlice < j) and (startSlice < endSlice) then
  begin
    Result:=TList.Create;
    j:=endSlice - startSlice + 1;
    Result.Capacity:=j;
    for j:=startSlice to endSlice do
      Result.Add(Items[j]);
  end;
end;

So I must "transfer" the items to the new list, through a loop, one by one. Thank you.

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Obtain a sublist from a TList
« Reply #3 on: August 17, 2014, 08:53:19 pm »
Well, you could optimise it with a block memory move. I just dashed off the simplest code that occurred to me.
« Last Edit: August 17, 2014, 08:54:50 pm by howardpc »

 

TinyPortal © 2005-2018