如何在LINQ中使用whereif [英] How to use whereif in LINQ

查看:774
本文介绍了如何在LINQ中使用whereif的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我如何最好地使用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);
     }

我想我们可以通过使用whereif来使这个查询变得非常简单吗?有人可以通过使用whereif来帮助我如何简化这个查询吗?而不是检查是否(empid ==)?

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 == "") ?

是否可能?

推荐答案

我相信如果它不为空,你想通过empId进行过滤。简单的OR运算符将完成这项工作:

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

这篇关于如何在LINQ中使用whereif的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆