How to make a compound “or” clause in Linq?

前端 未结 5 1701
南笙
南笙 2021-01-05 23:00

If you\'re adding \"and\" conditions to a Linq query, it\'s easy to do it like so:

var q = MyTable;
if (condition1)
  q = q.Where(t => t.Field1 == value1)         


        
5条回答
  •  没有蜡笔的小新
    2021-01-05 23:48

    You can use a PredicateBuilder and use it to build an Or based expression:

     var predicate = PredicateBuilder.False();
    
     predicate = predicate.Or (t => t.Field1 == value1);
     predicate = predicate.Or (t => t.Field2 > t.Field3);
    
     q = q.Where (predicate);
    

    You can read more about it here: http://www.albahari.com/nutshell/predicatebuilder.aspx

    Replace the Product in PredicateBuilder.False() with your queried object.

    Note that you start from a False predicate as you want to use Or. If You'd want an And predicate, Yuo should start from a True

提交回复
热议问题