So I have the following where conditions
sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent)) ||
y.session.ROOM.ToUpper().Contains(SearchContent) ||
y.session.COURSE.ToUpper().Contains(SearchContent));
I want to split this into multiple lines based on whether a string is empty for example:
if (!String.IsNullOrEmpty(Division)) {
sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent)));
}
if (!String.IsNullOrEmpty(Room)) {
// this shoudl be OR
sessions = sessions.Where(y => y.session.ROOM.ToUpper().Contains(SearchContent));
}
if (!String.IsNullOrEmpty(course)) {
// this shoudl be OR
sessions = sessions.Where(y => y.session.COURSE.ToUpper().Contains(SearchContent));
}
If you notice I want to add multiple OR conditions split based on whether the Room, course, and Division strings are empty or not.
There are a few ways to go about this:
Apply the "where" to the original query each time, and then
Union()
the resulting queries.Do Expression manipulation to merge the bodies of your lambda expressions together, joined by
OrElse
expressions. (Complicated unless you've already got libraries to help you: after joining the bodies, you also have to traverse the expression tree to replace the parameter expressions. It can get sticky. See this post for details..Where()
assumes logicalAND
and as far as I know, there's no out of box solution to do it. If you want to separateOR
statements, you may want to look into using Predicate Builder or Dynamic Linq.You can create an extension method to conditionally apply the filter:
And use it like this: