Don Tomato
Don Tomato

Reputation: 3509

LINQ dynamic query for entity framework

I have two Guid collections:

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

How to make the following query:

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

Collections could be empty and in this case we shouldn't add an appropriate 'AND' condition. How to do such dynamic query?

UPDATE

Hmm, imagine I need something like this:

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

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

How to do that?

Upvotes: 1

Views: 1135

Answers (3)

Bazzz
Bazzz

Reputation: 26912

First answer based on question
Selects only those Activity objects of which the StatusID is in statusses and the PriorityID is in priorities. Obviously if the collections are empty none of the Activity objects will match the condition.

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

Alternative answer based on @Don Tomato's comment
There must have been a misunderstanding based on the way you formulated the question. However, I think what you want is to add conditions to an IQueryable as required.

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

Upvotes: 5

Mario S
Mario S

Reputation: 11945

You could also do it like this:

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.

But I guess what you really want to do is as @Bazzz answered.

Upvotes: 0

beyond-code
beyond-code

Reputation: 1422

You can chain where clauses together like this and the end result is that they will be anded together:

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

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

query.ToList();

Upvotes: 0

Related Questions