有人知道通过使用扩展方法获得列表框控件中所有选定项目的顺畅方法吗?
而且,请告诉我,关于如何获得这样一个列表是无关紧要的,因为最终一切都使用循环迭代项目并找到所选择的项目.
Rub*_*ias 28
var selected = yourListBox.Items.GetSelectedItems();
//var selected = yourDropDownList.Items.GetSelectedItems();
//var selected = yourCheckBoxList.Items.GetSelectedItems();
//var selected = yourRadioButtonList.Items.GetSelectedItems();
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(
this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}
Run Code Online (Sandbox Code Playgroud)
扩展方法:
public static List<ListItem> GetSelectedItems(this ListBox lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
Run Code Online (Sandbox Code Playgroud)
您可以在列表框中调用它,如:
List<ListItem> selectedItems = myListBox.GetSelectedItems();
Run Code Online (Sandbox Code Playgroud)
您还可以使用列表框项目上的"投射"进行转换,例如:
return lst.Items.Cast<ListItem>().Where(i => i.Selected).ToList();
Run Code Online (Sandbox Code Playgroud)
不确定哪个会表现更好OfType或Cast(我的预感是Cast).
根据Ruben对一般ListControl方法的反馈进行编辑,这确实会使它成为更有用的扩展方法:
public static List<ListItem> GetSelectedItems(this ListControl lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22641 次 |
| 最近记录: |