Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use whereif in LINQ

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?

like image 664
jestges Avatar asked Dec 21 '22 10:12

jestges


2 Answers

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);
like image 181
Sergey Berezovskiy Avatar answered Mar 11 '23 20:03

Sergey Berezovskiy


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;
}
like image 37
Daniel Hilgarth Avatar answered Mar 11 '23 19:03

Daniel Hilgarth