Search code examples
delphitlisttlistbox

Convert strings in ListBox to List<String>


TListBox component contains a set of rows (strings). How can I get this set as a list TList ? The code examples below, do not give the desired result. (Сode does not compile)

MyList  := TList<String>.Create(MyListBox);
MyList  := TList<String>.Create(MyListBox.Items);
MyList  := TList<String>.Create(MyListBox.Items.ToStringArray);

Is it possible to do this without using a loop or not? Thanks!


Solution

  • You can do this:

    MyList := TList<string>.Create;
    try
      MyList.AddRange(MyListBox.Items.ToStringArray);
      ....
    finally
      MyList.Free;
    end;
    

    If you wanted to assign the items in the constructor you'd need an instance of TEnumerable<string>. That's not easy to graft on to TStrings from the outside. So I think the above code is probably the cleanest.