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?
Maybe this helps:
IEnumerable<MyClass> items = yourListBox.SelectedItems.Cast<MyClass>();
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With