Forum > Beginners

Obtain a sublist from a TList

(1/1)

py2pa:
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: ---new_sublist = source_list[from_element:to_element]
--- End code ---

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:
A simple-minded descendant of this sort should do it


--- Code: ---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;

--- End code ---

py2pa:

--- Quote from: howardpc on August 17, 2014, 08:25:34 pm ---A simple-minded descendant of this sort should do it


--- Code: ---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;

--- End code ---

--- End quote ---

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

howardpc:
Well, you could optimise it with a block memory move. I just dashed off the simplest code that occurred to me.

Navigation

[0] Message Index

Go to full version