Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SelectedObjectCollection to Collection of Specific Type

I have a WinForms multiselect listbox, and each item in the listbox is of type MyClass.

I am also writing a method that needs to take a parameter that is a collection of MyClass. It could be of type MyClass[], List<MyClass>, IList<MyClass>, IEnumerable<MyClass>, etc. Any of those would work fine.

Somehow, I need to pass the selected items in the listbox to my method. But how would I convert SelectedObjectCollection to any of the MyClass collection types described above?

like image 948
Jonathan Wood Avatar asked Dec 29 '25 03:12

Jonathan Wood


2 Answers

Maybe this helps:

IEnumerable<MyClass> items = yourListBox.SelectedItems.Cast<MyClass>();
like image 110
King King Avatar answered Dec 30 '25 15:12

King King


One issue is that ListBox Items are not a generic list, so it could contain more than one type. If you call on .AsQueryable you are making the explicit cast on a non type-safe collection when you call on .Select(), Same goes with calling .Cast<T>, as you could get a cast exception. A safer approach would be to use .OfType<T>()

IEnumerable<MyClass> selected = listBox.SelectedItems.OfType<MyClass>();
like image 43
Patrick Magee Avatar answered Dec 30 '25 15:12

Patrick Magee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!