I have a page where user is provided with four search fields. I am suppose to take the intersection of the fields and display the results. However the user isn’t required to fill in all of the fields.
In my controller i have the following code.
string subject = (string)Session[d.sessionSearchSubject];
string courseNumber = (string)Session[d.sessionSearchCourseNum];
string yearLev = (string)Session[d.sessionSearchYearLev];
string period = (string)Session[d.sessionSearchPer];
if (!(subject.Equals("") && courseNumber.Equals("") && yearLev.Equals("") && period.Equals("")))
{
db.Courses.Where(a => a.subject.Equals(subject) && a.coursenumber.Equals(courseNumber) && a.period.Equals(period...
}
else if (!(subject.Equals("") && courseNumber.Equals("") && yearLev.Equals("")))
{
// Query the database.
}
else if (!(subject.Equals("") && courseNumber.Equals("") && period.Equals("")))
{
// Query the database.
}
else if (!(subject.Equals("") && yearLev.Equals("") && period.Equals("")))
...
As you can see there will be a lot of if statements. I was wondering if there is a better way to do this? i.e. a single query statement that ignores the field if its empty. Or if i can replace the empty string with something that would be equivalent to “any” ???
You could break the results into four statements, corresponding to each of the four criteria:
keeps it clean and extensible, while also only attaching the conditions to the sql query that are necessary.