gpt4 book ai didi

linq - 如何在 LINQ 中使用 whereif

转载 作者:行者123 更新时间:2023-12-02 07:37:41 25 4
gpt4 key购买 nike

嗨,有人可以帮助我如何最好地在 LINQ 中使用 whereif

IQueryable<Employee> empQuery;
if (empId == "")
{
empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => x.Id == empId);
}
else
{
empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code);
}

我认为我们可以通过使用 whereif 使这个查询变得非常简单,对吗?有人可以帮助我如何使用 whereif 使这个查询变得简单吗?而不是检查 if (empid == "") ?

是否可以?

最佳答案

如果 empId 不为空,我相信您希望按 empId 进行过滤。简单的 OR 运算符将完成这项工作:

IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" || x.Id == empId);

您也可以动态构建查询:
IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code);

if (empId != "")
empQuery = empQuery.Where(x => x.Id == empId);

关于linq - 如何在 LINQ 中使用 whereif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14771990/

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