Riz
Riz

Reputation: 6982

Linq to Entity - How to concatenate conditions

I am writing a Linq Query. Is there a way that I can concatenate to query based on some if conditions?

Like on query is

    from res in _db.Person
    where res.Departments.ID == deptId
    select res;

And if I have a condition true, I would like it to be something like

from res in _db.Person
    where res.Departments.ID == deptId && res.Departments.Type == deptType
    select res;

Upvotes: 0

Views: 3041

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500525

Implementing an "AND" type condition is easy - and easier using extension method syntax to call Where multiple times:

IQueryable<Person> people = _db.Person
                               .Where(res => res.Departments.ID == deptId);
if (deptType != null)
{
    people = people.Where(res => res.Departments.Type == deptType);
}

// Potentially add projections etc.

EDIT: If you want "OR" functionality, it's slightly tricky from scratch, as you need to mess around with expression trees. I suggest you use the PredicateBuilder library:

Expression<Func<Person, bool> predicate = res => res.Departments.ID == deptId;
if (deptType != null)
{
    predicate = predicate.Or(res => res.Departments.Type == deptType);
}
IQueryable<Person> people = _db.Person.Where(predicate);

Upvotes: 6

Bob Vale
Bob Vale

Reputation: 18474

Assuming your condition is in the variable condition

from res in _db.Person
where res.Departments.ID == deptId && (!condition || res.Departments.Type == deptType)
select res;

Version that does or as requested

from res in _db.Person
where res.Departments.ID == deptId || (condition && res.Departments.Type == deptType))
select res;

Alternatively you may wish to use predicate builder

Upvotes: 3

CodingGorilla
CodingGorilla

Reputation: 19842

I would do something like this:

var result = _db.Person.Where(x=>x.Departments.ID == deptId);
if(myCondition)
   result = result.Where(x=>x.Departments.Type == deptType);

The query is not actually executed until you attempt to enumerate result, so you can keep adding conditions as long as you like.

Upvotes: 1

Related Questions