开发者

How to assign Objects from ListBox to ArrayList in a single statement?

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 t开发者_如何学Gohrough each objects in the ListBox items and add it to ArrayList.

How would you do it?

Thanks in advance.


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


You should use the AddRange() method of ArrayList.

The equivalent to your Delphi code is:

theUser.Groups.Clear();
theUser.Groups.AddRange(ListBox1.Items);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜