I have a search form that looks like this:
The code behind the form looks like this:
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div>
@Html.DropDownList("SelectedType", Model.TypeOptions)
@Html.DropDownList("SelectedSearch", Model.SearchOptions)
@Html.TextBoxFor(x => x.SearchTerm)
<input type="submit" value="Search" />
</div>
}
What I want to do is dynamically construct a lambda where clause from the return options. E.g. if the user selects "Process No" and "Contains" then the lambda would look like
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No.Contains(SearchTerm));
Or if the user selects "PLC No" and "Equals" then the lambda would look like
model.DataSource = _db.InstrumentLists.Where(x => x.PLC_No == SearchTerm);
I am trying to do this while avoiding a big case statement or an if stack, i.e. I don't want the following:
if (SelectedType == "Process No" And SelectedSearch = "Contains")
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No.Contains(SearchTerm));
elseif (SelectedType == "Process No" And SelectedSearch = "Equals")
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No == SearchTerm);
...
Essentially I want to pass a reference to a class property, something to specify the test type (i.e contains, equals, starts with, etc) and a search term to a function, or something along those lines, and get back a predicate to put into my Where clause. I want this function to work dynamically so I shouldn't have to modify it for every combination of property and test type.
Is this possible or is the only way to use Where with a string predicate parameter?
Edit: In case its important, I'm use EF for my data model so _db.InstrumentLists returns an ObjectSet<InstrumentList>
.