locked
combine 2 Linq Expressions RRS feed

  • Question

  • How to combine 2 linq expressions

                       var stats = from s in context.Stats                                                                                                  
                                select s;
    
                        Expression<Func<Stat, bool>> e1 = s => s.Age >= 15 && s.Age < 25;
                        Expression<Func<Stat, bool>> e2 = s => s.Age >= 40 && s.Age < 50;
    
                        stats = stats.Where(e1);

    This code works.

    Now, I want to combine e1 and e2 in a OR expression. 

    thanks

    Thursday, November 15, 2012 4:50 PM

Answers

  • Do you want to end up with the equivalent of :

    Expression<Func<Stat, bool>> e3 = s => s.Age >= 15 && s.Age < 25 || s.Age >= 40 && s.Age < 50;

    LinqKit coud be useful for you. Use the PredicateBuilder to create an expression and combine it with further expressions as below...

                Expression<Func<Stat, bool>> e1 = s => s.Age >= 15 && s.Age < 25;
                Expression<Func<Stat, bool>> e2 = s => s.Age >= 40 && s.Age < 50;
    
                var predicate = PredicateBuilder.True<Stat>();
    
                predicate = predicate.And(e1);
                predicate = predicate.Or(e2);
    
                var res = Stats.Where(predicate.Compile()).ToList();

    Hope this helps.

    • Edited by JayChase Friday, November 16, 2012 2:05 AM
    • Proposed as answer by Mr. Javaman II Friday, November 16, 2012 2:19 AM
    • Marked as answer by Stephane Savioz Friday, November 16, 2012 9:35 AM
    Friday, November 16, 2012 2:04 AM

All replies

  • Do you want to end up with the equivalent of :

    Expression<Func<Stat, bool>> e3 = s => s.Age >= 15 && s.Age < 25 || s.Age >= 40 && s.Age < 50;

    LinqKit coud be useful for you. Use the PredicateBuilder to create an expression and combine it with further expressions as below...

                Expression<Func<Stat, bool>> e1 = s => s.Age >= 15 && s.Age < 25;
                Expression<Func<Stat, bool>> e2 = s => s.Age >= 40 && s.Age < 50;
    
                var predicate = PredicateBuilder.True<Stat>();
    
                predicate = predicate.And(e1);
                predicate = predicate.Or(e2);
    
                var res = Stats.Where(predicate.Compile()).ToList();

    Hope this helps.

    • Edited by JayChase Friday, November 16, 2012 2:05 AM
    • Proposed as answer by Mr. Javaman II Friday, November 16, 2012 2:19 AM
    • Marked as answer by Stephane Savioz Friday, November 16, 2012 9:35 AM
    Friday, November 16, 2012 2:04 AM
  • Yes the Albahari brothers did a nice job on LinqKit by abstracting the need to learn Expressions (yuck).

    JP Cowboy Coders Unite!


    Friday, November 16, 2012 2:19 AM
  • I finally used PredicateBuilder as suggested and it fits my needs.

    thanks again

    Friday, November 16, 2012 9:36 AM