How to use whereif in LINQ

邮差的信 提交于 2019-12-02 03:16:02

问题


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?


回答1:


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);



回答2:


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;
}



回答3:


.Where(x => x.Id == empId);

Doesn't make sense if the value is '""' - what do you expect it to return?

 var query = (from items in dbContext.Emps
              where items.Id == empId
              select new { 
                          Name = items.Name,
                          Code = items.Code
              }).ToList();


来源:https://stackoverflow.com/questions/14771990/how-to-use-whereif-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!