根据某些参数过滤Linq查询

时间:2013-02-04 16:03:52

标签: c# linq entity-framework

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

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为真,那么如果includeExpired,则会包含有效文档如果是,那么过期的文件将被包括在内,等等,我可以将所有三个真实,或者其中一个或两个是真的。我不希望对DB有多个调用。有一个逻辑可以通过一次调用来做到这一点吗?

4 个答案:

答案 0 :(得分:5)

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

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. 

答案 1 :(得分:1)

您可以使用PredicateBuilder实施。使用此类,您可以在linq查询上应用一些过滤器。像这样:

public IEnumerable<Document> GetDocumentsList(Guid? sessionID, bool? includeValid, bool? includeExpired, bool?  includeAboutToExpire)
{
    var query = db.Documents;

    if (sessionID.HasValue)
       query = query.And(x => x.SessionID = sessionID.Value);

    if (includeValid.HasValue && includeValid.Value)
       query = query.And(x => x.IncludeValid = includeValid.Value);

    // others parameters...

    return query.ToList();
}

PredicateBuilder实现

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

答案 2 :(得分:0)

看起来您需要加入文档和状态。此外,条件(!includeValid || d.Valid)可让您过滤有效的文档,只有includeValid标识为true

public List<Document> GetDocumentsList(Guid sessionID, 
       bool includeValid, bool includeExpired, bool includeAboutToExpire)
{
   using (DB db = new DB())
   {
       // get the active documents
       var docs = from d in db.Documents
                  join s in db.EmployeeStatuses on d.EmpID equals s.EmpID
                  where s.StatusEndDate == null &&
                        s.Status == "Active" &&
                        (!includeValid || d.Valid) &&
                        (!includeExpired || d.Expired) &&
                        (!includeAboutToExpired || d.AboutToExpired)
                  select d;

        return docs.ToList()
    }
}

答案 3 :(得分:0)

这是怎么回事? (我正在假设当然应该如何评估这些标志)。

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"
                                 || (includeValid && s.Status == "Valid")
                                 || (includeExpired && s.Status == "Expired")
                                 || (includeAboutToExpired && s.Status == "AboutToExpired") ))
                        );

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

        return docs.ToList()
    }
}