how to create a dynamic linq query based on search criteria

advertisements

I have a search form which i want to use to search a database for data. The searchbox has 4 checkboxes and 1 textfield. The problem is how do i build the linq query considering i dont know beforehand what textboxes the user will check for filtering the search. What i have so far is:

[HttpPost]
public ActionResult search(string ulv, string bjorn, string jerv, string gaupe)
{
    var query = (from o in db.observasjonene select o);
    if (ulv != null)
    {
        query = query.Where(o => o.art == ulv);
    }
    if (bjorn != null)
    {
        query = query.Where(o => o.art == bjorn);
    }
    if (jerv != null)
    {
        query = query.Where(o => o.art == jerv);
    }
    if (gaupe != null)
    {
        query = query.Where(o => o.art == gaupe);
    }
    IEnumerable ls = query.ToList();
    return Json(ls, JsonRequestBehavior.AllowGet);

}

The problem with the "where" clause is that if a condition is true, it overwrites the results from the earlier condition. I guess i need an "or" statement or something..


If I have understood your question correctly, you want to check if art equals to any of provided values. You can combine those values into collection and check if collection contains art value:

var values = new [] { ulv, bjorn, jerv, game }.Where(v => v != null);
var query = from o in db.observasjonene
            where values.Contains(o.art)
            select o;

EF translates Contains into SQL IN operator.