gpt4 book ai didi

c# - 根据用户选择的复选框为多列生成 LINQ 或 Lambda 表达式

转载 作者:行者123 更新时间:2023-11-30 15:06:27 24 4
gpt4 key购买 nike

我的网页顶部有几个复选框,它们对应于我的表格的列。就像有一列 studentId 然后会有一个复选框 studentId 等等。我想为 List 编写这样一个 linq/lamda 表达式,它将根据选中的复选框进行过滤。例如,如果选择 studentId 和 studentType 复选框,那么 linq/lambda 表达式应该带来与选择匹配的所有行。

例子:

如果检查了 studentId 和 studentType 则:

foreach (Child c in SomeList)
{
if (chkStudentId.checked)
{
List.FindAll (h=> h.StudentId == c.studentId);
}
if (chkStudentType.checked)
{
List.FindAll (h => h.StudentType == c.studentType)
}
}
}

我不知道如何编写这样的代码,如果用户选择多个复选框,查询应该与所有列进行比较,并仅根据选中的复选框获取值。以上只是静态的,没有帮助。请帮忙。谢谢。

最佳答案

如果您希望您的查询是完全动态的,那么表达式树是一个很大的帮助。但是如果复选框的数量是静态的你也可以选择下面的解决方案:

var students = <your list of students>.AsQueryable();

if ( chkStudentId.checked)
{
students = students.Where(s => s.StudentId == c.StudentId);
}

if (chkStudentType.checked))
{
students = students.Where(s => s.StudentType== h.StudentType);
}

通过这种方式,您可以动态组合 where 子句。

关于c# - 根据用户选择的复选框为多列生成 LINQ 或 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7845494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com