C# LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1196007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ: Get all selected values of a CheckBoxList using a Lambda expression
提问by p.campbell
Consider a scenario where you want to retrieve a List
or IEnumerable
of the values of all the selected checkboxes in an <asp:CheckBoxList>
.
考虑要检索的场景List
或IEnumerable
在所有选中的复选框的值<asp:CheckBoxList>
。
Here's the current implementation:
这是当前的实现:
IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>()
where item.Selected
select int.Parse(item.Value));
Question: How would you improve this LINQ query using a lambda expression or lambda syntax?
问题:您将如何使用 lambda 表达式或 lambda 语法改进此 LINQ 查询?
采纳答案by Andrew Hare
You areusing lambda expressions - they are just concealed by your use of C#'s query operators.
您正在使用 lambda 表达式 - 它们只是被您使用 C# 的查询运算符所隐藏。
Consider that this:
考虑一下:
IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>()
where item.Selected
select int.Parse(item.Value));
Gets compiled to this:
编译成这样:
IEnumerable<int> allChecked = chkBoxList.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => int.Parse(i.Value));
As you can see you are already using two lambda expressions (they are the parameters to the Where
and Select
methods) and you didn't even know it! This query is fine and I wouldn't change it at all.
正如您所看到的,您已经在使用两个 lambda 表达式(它们是Where
和Select
方法的参数),而您甚至都不知道!这个查询很好,我根本不会改变它。
回答by Jon Skeet
I would improve the query expression by making the call to Cast<T>
implicit:
我将通过调用Cast<T>
隐式来改进查询表达式:
IEnumerable<int> allChecked = from ListItem item in chkBoxList.Items
where item.Selected
select int.Parse(item.Value);
When you specify the type of a range variable, the compiler inserts a call to Cast<T>
for you.
当您指定范围变量的类型时,编译器会Cast<T>
为您插入对 的调用。
Other than that, I entirely agree with Andrew.
除此之外,我完全同意安德鲁。
EDIT: For GONeale:
编辑:对于GONeale:
IEnumerable<int> allChecked = chkBoxList.Items
.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => int.Parse(item.Value));