Joining multiple where clauses in LINQ as OR instead of AND

前端 未结 7 946
情书的邮戳
情书的邮戳 2020-12-16 13:33

Is there anyway to join LINQ where clauses as OR ?

var ints = new [] { 1, 3, 5, 7 };

var query = from i in ints select i;

query = query.Where (q => q ==         


        
7条回答
  •  情书的邮戳
    2020-12-16 14:08

    If you want to stay with your strong-typing Linq queries you should look into LinqKit and predicate building. I have used this for something similar and found it to work well with And / Or stacking of filters.

    Check out the C#4.0/3.0 in a Nutshell excerpt for more in depth info. Here is a snip from my code:

            //Setup the initial predicate obj then stack on others:
            basePredicate = basePredicate.And(p => false);
            var predicate1 = PredicateBuilder.True();
    
            foreach (SearchParms parm in parms)
            {
                switch (parm.field)
                {
                    case "firstname":
                        predicate1 = predicate1.And(p => p.FirstName.Trim().ToLower().Contains(sValue));
                        break;
                    //etc...
                }
    
            }
            //Run a switch based on your and/or parm value to determine stacking:
            if (Parm.isAnd) {
                 basePredicate = basePredicate.And(predicate1);
            } else {
                 basePredicate = basePredicate.Or(predicate1);
            }
    

提交回复
热议问题