c# - 有条件地应用 Where(或在它们之间)LINQ

标签 c# linq functional-programming conditional-statements

我在我的 asp.net 项目中有过滤器,并希望将表达式添加到此列表中,条件为:

Expression<Func<MyModel, bool>> func;
var list = new List<Expression<Func<MyModel, bool>>>();

我想有条件地应用 Where(或在它们之间)。例如:

if(sth){
   func = p => p.a <= b;
   list.Add(func);
}
if (sth else){
   func = p => p.c >= d;
   list.Add(func);
}

var fq = Session.Query<MyModel>();
fq = list.Aggregate(fq, (current, expression) => current.Where(expression));

我该怎么做?

最佳答案

您可以构建一个扩展方法,使用 OR 关系合并两个条件表达式,如下所示:

public static class Extensions
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> one, Expression<Func<T, bool>> another)
    {
        var parameter = one.Parameters[0];
        var visitor = new ReplaceParameterVisitor(parameter);
        another = (Expression<Func<T, bool>>)visitor.Visit(another);
        var body = Expression.Or(one.Body, another.Body);
        return Expression.Lambda<Func<T, bool>>(body, parameter);
    }
}

class ReplaceParameterVisitor : ExpressionVisitor
{
    public ParameterExpression NewParameter { get; private set; }

    public ReplaceParameterVisitor(ParameterExpression newParameter)
    {
        this.NewParameter = newParameter;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        return this.NewParameter;
    }
}

使用和测试代码:

Expression<Func<int, bool>> condition1 = x => x > 8;
Expression<Func<int, bool>> condition2 = y => y < 3;            
var condition = condition1.Or(condition2);
var result = Enumerable
    .Range(1, 10)
    .Where(condition.Compile())
    .ToList();      //1,2,9,10

关于c# - 有条件地应用 Where(或在它们之间)LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37110491/

相关文章:

c# - 俄罗斯方 block 清晰的线条问题

string - 如何在 haskell 中正确定义空字符串?

scala - 使用数组作为 Scala foldLeft 累加器

c - Haskell 中的高阶函数到底能做什么扩展 C 不能做的事情?

c# - 从 C# 中的参数化构造函数调用无参数构造函数?

c# - 如何抽象一个单例类?

c# - 如何为 Asp.net MVC 中的每个登录创建 session ID?

c# - 只选择一个时间间隔内的第一条记录

c# - 动态创建 Func<T,TR> C#

c# - List.except 自定义类