How to combine two LINQ Expressions?
Asked Answered
B

4

5

I have the following LINQ query in c#

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 and gives me the rows from the Stats table where Age is between 15 an 25.

Now, i would like to get the rows from 15 to 25 AND from 40 to 50.

How do I combine those 2 expressions ?

thanks

Bestead answered 15/11, 2012 at 16:43 Comment(0)
S
8

It's a bit ugly but if you want to keep them as expressions:

stats = stats.Where(s => (e1.Compile()(s) || e2.Compile()(s))).ToList();

If you can change them to Funcs it's cleaner:

Func<Stat, bool> e1 = s => s.Age >= 15 && s.Age < 25;
Func<Stat, bool> e2 = s => s.Age >= 40 && s.Age < 50;

stats = stats.Where(s => e1(s) || e2(s)).ToList();
Salaam answered 15/11, 2012 at 16:49 Comment(0)
A
7

How about...

Expression<Func<Stat, bool>> e1 = s => 
   (s.Age >= 15 && s.Age < 25) || (s.Age >= 40 && s.Age < 50);
Adamsite answered 15/11, 2012 at 16:46 Comment(3)
Hum, that works. But I would like to do something like that : stats.Where(e1 || e2) but no successBestead
@Bestead In that case I like juharr's solution the best stats = stats.Where(e1).Union(stats.Where(e2));Adamsite
That solution returns all table rowsBestead
E
2

You could do a Union like this

stats = stats.Where(e1).Union(stats.Where(e2));
Escapade answered 15/11, 2012 at 17:5 Comment(0)
A
1
Expression<Func<Stat, bool>> GetOrExpression(
    Expression<Func<Stat, bool>> e1,
    Expression<Func<Stat, bool>> e2)
{
    return s => e1.Compile()(s) || e2.Compile()(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(GetOrExpression(e1, e2));
Aspirant answered 15/11, 2012 at 16:49 Comment(1)
since e1/e2 are expressions you will need to do e1.Compile(s) || e2.Compile(s)Papa

© 2022 - 2024 — McMap. All rights reserved.