以编程方式在Linq中使用条件

Mik*_*e B 7 c# linq linq-to-sql

我刚刚阅读了最近关于在Linq中使用条件的问题,它让我想起了一个我无法解决的问题.在以编程方式构建Linq to SQL查询时,如果在运行时之前不知道条件数,那么如何才能完成此操作?

例如,在下面的代码中,第一个子句创建一个IQueryable,如果执行它,将选择数据库中的所有任务(称为问题),第二个子句将优化为仅分配给一个部门的问题(如果已在一个部门中选择了一个) combobox(将其选中的项目绑定到departmentToShow属性).

我怎么能使用selectedItems集合呢?

IQueryable<Issue> issuesQuery;

// Will select all tasks
issuesQuery = from i in db.Issues
              orderby i.IssDueDate, i.IssUrgency
              select i;

// Filters out all other Departments if one is selected
   if (departmentToShow != "All")
   {
        issuesQuery = from i in issuesQuery
                      where i.IssDepartment == departmentToShow
                      select i;
    }
Run Code Online (Sandbox Code Playgroud)

顺便说一下,上面的代码被简化了,在实际代码中有大约十几个子句根据用户搜索和过滤器设置细化查询.

Aar*_*ght 7

如果条件的数量未知,那么使用lambda语法而不是查询理解会更容易,即:

IQueryable<Issue> issues = db.Issues;
if (departmentToShow != "All")
{
    issues = issues.Where(i => i.IssDepartment == departmentToShow);
}
issues = issues.OrderBy(i => i.IssDueDate).ThenBy(i => i.IssUrgency);
Run Code Online (Sandbox Code Playgroud)

(假设您希望在过滤之后进行排序,这应该是这种情况 - 如果您尝试先进行排序,我不确定Linq是否会生成优化查询).

如果你有大量的可选条件,那么你可以使用谓词来清理它:

List<Predicate<Issue>> conditions = new List<Predicate<Issue>>();
if (departmentToShow != "All")
    conditions.Add(i => i.IssDepartment == departmentToShow);
if (someOtherThing)
    conditions.Add(anotherPredicate);
// etc. snip adding conditions

var issues = from i in issues
             where conditions.All(c => c(i))
             orderby i.IssDueDate, i.IssUrgency;
Run Code Online (Sandbox Code Playgroud)

或者只使用PredicateBuilder,这可能更容易.