Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic Linq query based on property values

Tags:

c#

linq

I have a class that contains a number of properties of type bool.

public class FilterModel 
{
    public bool Hotel { get; set; }
    public bool Apartment { get; set; }
    public bool Guesthouse { get; set; }

}

I am constructing a LINQ query dynamically based on whether or not these properties are true or false. For example if I had an instance of this class and Hotel was set to true. I want to generate a LINQ query something like

var q = from accom in db.Accommodation
                     where accom.Hotel == true 
                     select accom;

Thanks in advance

like image 579
Barry Avatar asked Nov 29 '25 08:11

Barry


2 Answers

Are you looking for something like this?

IQueryable<Accommodation> query = db.Accommodation;

if (filterModel.Hotel)      query = query.Where(a => a.Hotel);
if (filterModel.Apartment)  query = query.Where(a => a.Apartment);
if (filterModel.Guesthouse) query = query.Where(a => a.Guesthouse);

return query;
like image 161
dtb Avatar answered Nov 30 '25 23:11

dtb


You want something like this:

var filterModel = GetFilterModelFromSomewhere();
var q = db.Accomodation;

if (filterModel.Hotel)
    q = q.Where(accom => accom.Hotel);

if (filterModel.Apartment)
    q = q.Where(accom => accom.Apartment);

if (filterModel.Guesthouse)
    q = q.Where(accom => accom.Guesthouse);

Since the query isn't executed until you enumerate it (via ToList() or an equivalent function) you can build it piecemeal in code based on dynamic conditions.

like image 29
John Bledsoe Avatar answered Nov 30 '25 21:11

John Bledsoe