3

In Delphi Prism, I need to assign objectcollection from ListBox to an ArrayList in a single statement. So far I have not found any solution.

In Delphi, this is how I did it.

theUser.Groups.Assign(ListBox1.Items);

Groups is a TList in Delphi and ArrayList in Delphi Prism. When I tried to do the same in delphi prism, it gives me the following errors.

"Groups.TGroupList" does not contain a definition for "Assign" in expression "theUser.groups.Assign"

If ArrayList doesn't have method that accepts objectcollection, then I will have to loop through each objects in the ListBox items and add it to ArrayList.

How would you do it?

Thanks in advance.

ThN
  • 3,235
  • 3
  • 57
  • 115

3 Answers3

5

Untested:

theUser.Groups.AddRange(ListBox1.Items)

ArrayList.AddRange accepts the ICollection interface which ListBox.ObjectCollection implements.

See also:

http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.aspx

http://msdn.microsoft.com/en-us/library/system.collections.arraylist.addrange(VS.71).aspx

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
2

You should use the AddRange() method of ArrayList.

The equivalent to your Delphi code is:

theUser.Groups.Clear();
theUser.Groups.AddRange(ListBox1.Items);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

If you don't need to add it to an existing list but just need it in a list, you could also use LINQ:

lbMyListBox.Items.Cast<String>().ToList();

The call to Cast() could be replaced by OfType() if you want to only select items of a certain type rather than invoking a casting error with invalid items as Cast does.

jamiei
  • 2,006
  • 3
  • 20
  • 28