Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to resize a TStringList?

I frequently find that I need to 'resize' a a TStringList to hold exactly N elements, either adding additional empty strings to the list, or deleting unneccessary ones.

On a C++ STL container I could use the resize method, but as that doesn't seem to exist, I usually do somethings like this (warning: pseudocode!).

list.beginUpdate;

while list.Count < requiredSize do
begin
   list.add('');
end;

while list.Count > requiredSize do
begin
   list.delete(list.count-1);
end;

list.endUpdate;

Is there a much simpler way of doing this that I've overlooked?

like image 789
Roddy Avatar asked Jan 13 '14 09:01

Roddy


2 Answers

Judging from the implementation of TStringList.Assign, there is no better way to do this. They basically call Clear and add the strings one by one.

You should of course put your code into a utility method:

procedure ResizeStringList(List : TStrings; ANewSize: Integer);
begin
...
end;

Or you could use a class helper to make your method appear to be part of TStringList itself.

like image 118
jpfollenius Avatar answered Oct 13 '22 00:10

jpfollenius


The method in your question is the best you can do. You can make it cleaner if you use a class helper. For instance:

type
  TStringsHelper = class helper for TStrings
    procedure SetCount(Value: Integer);
  end;

procedure TStringsHelper.SetCount(Value: Integer);
begin
  BeginUpdate;
  try
    while Count<Value do
      Add('');
    while Count>Value do
      Delete(Count-1);
  finally
    EndUpdate;
  end;
end;

And then you can write:

List.SetCount(requiredSize);
like image 30
David Heffernan Avatar answered Oct 12 '22 23:10

David Heffernan