大家好,有人可以帮助我如何在 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 == "") ?
是否可以?
我认为“whereif”应该是这个扩展方法。你不能使用它,因为它运行在IEnumerable<T>
而不是在IQueryable<T>
。结果是您将从数据库请求完整的员工表,并在应用程序的内存中执行过滤。那不是你想要的。但是,您可以使用条件运算符来实现此目的:
var empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" ? true : x.Id == empId);
请注意,这假设您的实际意思是if(empId != "")
在您的示例代码中。如果您不是这个意思,请交换第二个和第三个操作数:
.Where(x => empId == "" ? x.Id == empId : true);
话虽如此,您当然可以为以下内容创建相同的扩展方法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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)