Hi can someone help me how best we can use whereif in LINQ
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);
}
I think we can make this query very simple by using whereif right? Can someone help me how to make this query simple by using whereif? Instead of check if (empid == "") ?
Is it possible?
I believe you want filtering by empId if it is not empty. Simple OR operator will do the job:
IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" || x.Id == empId);
Also you can build query dynamically:
IQueryable<Employee> empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code);
if (empId != "")
empQuery = empQuery.Where(x => x.Id == empId);
I assume "whereif" is supposed to be this extension method. You can't use that, because it operates on an IEnumerable<T>
and not on a IQueryable<T>
. The result would be that you would request your complete employees table from the database and perform the filtering in memory in your application. That's not what you want. You can, however, use the conditional operator to achieve this:
var empQuery = dbContext.Emps
.Include(x => x.Name)
.Include(x => x.Code)
.Where(x => empId == "" ? true : x.Id == empId);
Please note that this assumes that you actually meant if(empId != "")
in your sample code. If you didn't mean this, switch the second and third operand around:
.Where(x => empId == "" ? x.Id == empId : true);
Having said this, you certainly can create the same extension method for IQueryable<T>
. It looks nearly the same, just has IEnumerable<T>
replaced with IQueryable<T>
and the predicate changed to an expression:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With