Adding criteria to a Linq query dynamically

18 Views Asked by At

What is the best way to build-up a dynamic query when some of the fields you want to filter on are not part of the returned result set.

The fictitious example below should demonstrate what I want to achieve, but I obviously can't filter on the reviewer in this way because it's not part of the result set. So can I achieve that in a dynamic way? There are multiple filters that might (and crucially might not) be applied to the query.

Whereas I could use an OR condition, it feels much cleaner to just apply the criteria that is required... but maybe that isn't possible?

IQueryable<TblProduct> query = from p in db.TblProduct
                   join r in db.TblReview on p.ProductID equals r.ProductID
                   select p;

// ...Other optional filters...

if (filterReviewerID.HasValue)
{
    query = query.Where(x => x.ReviewerID == filterReviewerID.Value);
}
0

There are 0 best solutions below