LINQ: Divide where OR conditions

So, I have the following condition:

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 several lines based on whether the line is empty:

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 that I want to add several sections of the OR conditions, based on whether the lines Room, course and Division are empty or not.

+5
source share
3 answers

There are several ways to do this:

  1. Apply "where" to the original request each time, and then Union()to the received requests.

    var queries = new List<IQueryable<Session>>();
    if (!String.IsNullOrEmpty(Division)) {
        queries.Add(sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent))));
    }
    
    if (!String.IsNullOrEmpty(Room)) {
    
        // this shoudl be OR
        queries.Add(sessions.Where(y => y.session.ROOM.ToUpper().Contains(SearchContent)));
    }
    
    if (!String.IsNullOrEmpty(course)) {
    
        // this shoudl be OR
        queries.Add(sessions.Where(y => y.session.COURSE.ToUpper().Contains(SearchContent)));
    }
    
    sessions = queries.Aggregate(sessions.Where(y => false), (q1, q2) => q1.Union(q2));
    
  2. , - , OrElse OrElse. (, , : , . . . .

  3. , PredicateBuilder, №2 .
+4

.Where() AND, , , . OR, Predicate Builder Linq.

+1

:

public static IQueryable<T> WhereIf<T>(
   this IQueryable<T> source, bool condition, 
   Expression<Func<T, bool>> predicate)
{
    return condition ? source.Where(predicate) : source;
}

:

using static System.String;

...

var res = sessions
   .WhereIf(!IsNullOrEmpty(Division), y => y.session.SESSION_DIVISION.ToUpper().Contains(SearchContent))
   .WhereIf(!IsNullOrEmpty(Room), y => y.session.ROOM.ToUpper().Contains(SearchContent))
   .WhereIf(!IsNullOrEmpty(course), y => y.session.COURSE.ToUpper().Contains(SearchContent)));
0

Source: https://habr.com/ru/post/1536668/


All Articles