LINQ: Split Where OR conditions

后端 未结 3 676
盖世英雄少女心
盖世英雄少女心 2021-01-18 23:35

So I have the following where conditions

sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent         


        
3条回答
  •  無奈伤痛
    2021-01-19 00:02

    You can create an extension method to conditionally apply the filter:

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

    And use it like this:

    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)));
    

提交回复
热议问题