LINQ:使用Lambda表达式获取CheckBoxList的所有选定值

p.c*_*ell 36 c# linq asp.net webforms

考虑一种情况,您想要检索一个ListIEnumerable多个所选复选框的值<asp:CheckBoxList>.

这是当前的实现:

IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>() 
                               where item.Selected 
                               select int.Parse(item.Value));
Run Code Online (Sandbox Code Playgroud)

问题:如何使用lambda表达式或lambda语法改进此LINQ查询?

And*_*are 87

正在使用lambda表达式 - 它们只是被您使用C#的查询运算符所隐藏.

考虑一下:

IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>() 
                               where item.Selected 
                               select int.Parse(item.Value));
Run Code Online (Sandbox Code Playgroud)

获取编译为:

IEnumerable<int> allChecked = chkBoxList.Items.Cast<ListItem>()
                              .Where(i => i.Selected)
                              .Select(i => int.Parse(i.Value));
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您已经在使用两个lambda表达式(它们是WhereSelect方法的参数),您甚至都不知道它!这个查询很好,我根本不会改变它.


Jon*_*eet 22

我将通过调用Cast<T>隐式来改进查询表达式:

IEnumerable<int> allChecked = from ListItem item in chkBoxList.Items 
                              where item.Selected 
                              select int.Parse(item.Value);
Run Code Online (Sandbox Code Playgroud)

指定范围变量的类型时,编译器会Cast<T>为您插入一个调用.

除此之外,我完全赞同安德鲁.

编辑:对于GONeale:

IEnumerable<int> allChecked = chkBoxList.Items
                                        .Cast<ListItem>()
                                        .Where(item => item.Selected)
                                        .Select(item => int.Parse(item.Value));
Run Code Online (Sandbox Code Playgroud)