Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a TList<T> in one step using Delphi?

I am sure this is a easy question, but I cannot get it to run:

var
  FMyList: TList<String>;
begin
  FMyList := TList<String>.Create(?????);
end;

How to insert instead of ????? to insert this 3 strings:

'one'
'two'
'three'

Thanks..

like image 920
ferpega Avatar asked Apr 24 '11 11:04

ferpega


2 Answers

Not a one liner, but a two liner:

FMyList := TList<String>.Create;
FMyList.AddRange(['one', 'two', 'three']);

Edit: Of course you can combine it with David's approach.

like image 177
Uwe Raabe Avatar answered Oct 21 '22 06:10

Uwe Raabe


There is no single method to do this. You could write your own constructor to do this as so:

constructor TMyList<T>.Create(const Values: array of T);
var
  Value: T;
begin
  inherited Create;
  for Value in Values do
    Add(Value);
end;

Then you could write:

FList := TMyList<string>.Create(['one', 'two', 'three']);

Update

As Uwe correctly points out in his answer, the code I present should use the AddRange() method:

constructor TMyList<T>.Create(const Values: array of T);
begin
  inherited Create;
  AddRange(Values);
end;
like image 37
David Heffernan Avatar answered Oct 21 '22 06:10

David Heffernan