1

我有两个 Guid 集合:

List<Guid> statuses;
List<Guid> priorities;

如何进行以下查询:

var result = context.Activity.Where(a => 
    (a.StatusID == statuses[0] || a.StatusID == statuses[1] || ... || a.StatusID == statuses[n]) &&
    (a.PriorityID == priorities[0] || a.PriorityID == priorities[1] || ... || a.PriorityID  == priorities[m]))

集合可能是空的,在这种情况下,我们不应该添加适当的“与”条件。如何做这样的动态查询?

更新

嗯,想象一下我需要这样的东西:

List<Func<Activity, bool>> conds = new List<Func<Activity, bool>>();

var result = context.Activity.Where(conds[0] || (conds[1] && conds[2]))

怎么做?

4

3 回答 3

5

基于问题的第一个答案
仅选择那些位于和 位于的Activity对象。显然,如果集合为空,则没有任何对象符合条件。StatusIDstatussesPriorityIDprioritiesActivity

var result = context.Activity.Where(a => 
    statuses.Contains(a.StatusID) && priorities.Contains(a.PriorityID));

基于@Don Tomato 的评论的替代答案基于
您提出问题的方式,一定存在误解。但是,我认为您想要的是IQueryable根据需要向 a 添加条件。

List<Func<Activity, bool>> conditions = new List<Func<Activity, bool>>();
// add conditions to the list
// for eaxmple:
// conditions.add(a => statuses.Contains(a.StatusID));
// or 
// conditions.add(a => a.Name == "Don Tomato");

IQueryable query = context.Activity.AsQueryable();
foreach (Func<Activity, bool> condition in conditions)
   query = query.Where(condition);

List<Activity> result = query.ToList();
于 2012-11-29T15:13:17.370 回答
0

您可以像这样将 where 子句链接在一起,最终结果是它们将被连接在一起:

var query = context.Activity.Where(o => <condition1>);

if (2ndconditionrequired)
{
    query = query.where(o => <condition2>);
}

query.ToList();
于 2012-11-29T15:14:35.933 回答
0

你也可以这样做:

var result = context.Activity;

if (statuses != null && statuses.Count > 0)
{
    result = results.Where(a => 
        a.StatusID == statuses[0] || a.StatusID == statuses[1] || ... || a.StatusID == statuses[n];
}

if (priorities != null && priorities.Count > 0)
{
    result = results.Where(a => 
        a.PriorityID == priorities[0] || a.PriorityID == priorities[1] || ... || a.PriorityID  == priorities[m]);
}

result.ToList(); // The query won't be executed until here.

但我想你真正想做的是@Bazzz 回答。

于 2012-11-29T15:15:09.933 回答