Extension method:
public static List<ListItem> GetSelectedItems(this ListBox lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
You can call it on your listbox like:
List<ListItem> selectedItems = myListBox.GetSelectedItems();
You could also do the conversion using a 'Cast' on the list box items like:
return lst.Items.Cast<ListItem>().Where(i => i.Selected).ToList();
Not sure which will perform better OfType
or Cast
(my hunch is Cast
).
Edit based on Ruben's feedback for a generic ListControl method which would indeed make it much more useful extension method:
public static List<ListItem> GetSelectedItems(this ListControl lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}