LINQ: Get all selected values of a CheckBoxList using a Lambda expression(LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值)
问题描述
考虑这样一种情况,您要检索 中所有选定复选框的值的 List 或 IEnumerable代码>.
Consider a scenario where you want to retrieve a List or IEnumerable of the values of all the selected checkboxes in an <asp:CheckBoxList>.
这是当前的实现:
IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>()
where item.Selected
select int.Parse(item.Value));
问题:您将如何使用 lambda 表达式或 lambda 语法改进此 LINQ 查询?
Question: How would you improve this LINQ query using a lambda expression or lambda syntax?
推荐答案
您在使用 lambda 表达式 - 它们只是被您使用 C# 的查询运算符所隐藏.
You are using lambda expressions - they are just concealed by your use of C#'s query operators.
考虑一下:
IEnumerable<int> allChecked = (from item in chkBoxList.Items.Cast<ListItem>()
where item.Selected
select int.Parse(item.Value));
编译成这样:
IEnumerable<int> allChecked = chkBoxList.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => int.Parse(i.Value));
如您所见,您已经在使用两个 lambda 表达式(它们是 Where 和 Select 方法的参数),而您甚至都不知道!这个查询很好,我根本不会改变它.
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.
这篇关于LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
