jes*_*ges 4 linq if-statement where-clause
嗨,有人可以帮助我如何最好地在 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);
}
Run Code Online (Sandbox Code Playgroud)
我认为我们可以通过使用 whereif 使这个查询变得非常简单,对吗?有人可以帮助我如何使用 whereif 使这个查询变得简单吗?而不是检查 if (empid == "") ?
是否可以?
我假设“whereif”应该是这个扩展方法。你不能使用它,因为它在 anIEnumerable<T>而不是在 a 上运行IQueryable<T>。结果是您将从数据库请求完整的员工表并在应用程序的内存中执行过滤。那不是你想要的。但是,您可以使用条件运算符来实现此目的:
var empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" ? true : x.Id == empId);
Run Code Online (Sandbox Code Playgroud)
请注意,这假设您实际上是if(empId != "")在示例代码中的意思。如果您不是这个意思,请交换第二个和第三个操作数:
.Where(x => empId == "" ? x.Id == empId : true);
Run Code Online (Sandbox Code Playgroud)
话虽如此,您当然可以为IQueryable<T>. 它看起来几乎一样,只是IEnumerable<T>替换为IQueryable<T>并且谓词更改为表达式:
public static IQueryable<TSource> WhereIf<TSource>(
this IQueryable<TSource> source,
bool condition,
Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
Run Code Online (Sandbox Code Playgroud)
如果 empId 不为空,我相信您希望按 empId 进行过滤。简单的 OR 运算符将完成这项工作:
IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" || x.Id == empId);
Run Code Online (Sandbox Code Playgroud)
您也可以动态构建查询:
IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code);
if (empId != "")
empQuery = empQuery.Where(x => x.Id == empId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11364 次 |
| 最近记录: |