简体   繁体   English

如何合并两个LINQ表达式?

[英]How to combine two LINQ Expressions?

I have the following LINQ query in c# 我在c#中有以下LINQ查询

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. 此代码有效,并为我提供了统计信息表中的年龄介于15至25之间的行。

Now, i would like to get the rows from 15 to 25 AND from 40 to 50. 现在,我想使行数从15到25,从40到50。

How do I combine those 2 expressions ? 如何结合这两个表达式?

thanks 谢谢

How about... 怎么样...

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

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 Func s it's cleaner: 如果您可以将它们更改为Func那么它会更清洁:

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();

你可以这样做一个联盟

stats = stats.Where(e1).Union(stats.Where(e2));
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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM