首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据某些参数过滤Linq查询

根据某些参数过滤Linq查询
EN

Stack Overflow用户
提问于 2013-02-05 00:03:52
回答 4查看 2.2K关注 0票数 0

我有下面的方法为我返回一些数据:

代码语言:javascript
复制
public List<Document> GetDocumentsList(Guid sessionID, bool includeValid, bool includeExpired, bool includeAboutToExpire)
{
   using (DB db = new DB())
   {
       // get the active documents
       var docs = db.Documents
                  .Where(d =>
                      db.EmployeeStatuses
                     .Any(s => s.EmpID == d.EmpID && s.StatusEndDate == null && s.Status == "Active")
                        );

        // how to filter the result depending on includeValid, includeExpired and includeAboutToExpired parameters?

        return docs.ToList()
    }
}

这里的问题是,我想根据bool参数过滤结果,例如,如果includeValid为true,则将包括有效文档,如果includeExpired为true,则将包括过期文档,以此类推,我可以将所有三个true或其中一个或两个true。我不希望有多个对DB的调用。有没有一种逻辑可以用一次调用就能做到这一点?

EN

Stack Overflow用户

发布于 2013-02-05 00:07:26

LinQ to entities defers execution until the results are enumerated。因此,添加后续.Where()语句不会导致对db的多次调用

代码语言:javascript
复制
var docs = db.Documents
                  .Where(d =>
                      db.EmployeeStatuses
                     .Any(s => s.EmpID == d.EmpID && s.StatusEndDate == null && s.Status == "Active")
                        );

if (includeValid)
   docs = docs.Where(x => [condition]);

//... and so on.

return docs.ToList(); // <- This is where the query is actually executed. 
票数 5
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14690572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档