C# Linq: Combine multiple .Where() with an *OR* clause

后端 未结 4 2123
不思量自难忘°
不思量自难忘° 2021-02-19 00:08

I have been searching a lot about my current problem but I could not find a real answer to solve that issue.

I am trying to build a LINQ Query that produces the followi

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 00:54

    You can use Expression to create in one step like this:

    Expression> exp = (model => 
                                        ((model.Field1.HasValue && c.Field1 == X) &&
                                        (model.Field2.HasValue && c.Field2 == X)) ||
                                         model.Field3 == X
                                        )
    

    Once you have your predicates defined, it's very easy to use them in a query.

    var result = Query.AsQueryable().Where(exp)
    

    Check the code in this gist: my gist url

    UPDATE 1: If You have to use steps to create your expression you can use this:

    Expression> exp = c => true;
    if (model.Field1.HasValue) 
    {
        var prefix = exp.Compile();
        exp = c => prefix(c) && c.Field1 == X;
    }
    
    if (model.Field2.HasValue) 
    {
        var prefix = exp.Compile();
        exp = c => prefix(c) && c.Field2 == X;
    }
    
    [...] like 20 more of these .Where() calls.
    

提交回复
热议问题