如何撰写Linq表达式?即Func <Exp <Func <X,Y >>,Exp <Func <Y,Z >>,Exp <Func <X,Z >>>

Eni*_*ity 14 .net c# linq linq-expressions

我正在创建一个Validator<T>班级.我正在尝试SelectMany为我的验证器实现Linq 扩展方法,以便能够使用Linq查询组合表达式,并在基础值发生更改时验证最终结果.

以下测试代码演示了我的意图.

var a = 2;
var b = 3;

var va = Validator.Create(() => a, n => n >= 0 && n < 5);
var vb = Validator.Create(() => b, n => n >= 0 && n < 5);

var vc = from ia in va
         from ib in vb
         select ia + ib;

Debug.Assert(vc.Value == a + b); //2 + 3
Debug.Assert(vc.Value == 5);

Debug.Assert(vc.IsValid == true);

a = 7;

Debug.Assert(vc.Value == a + b); //7 + 3
Debug.Assert(vc.Value == 10);

Debug.Assert(va.IsValid == false);
Debug.Assert(vb.IsValid == true);
Debug.Assert(vc.IsValid == false);
Run Code Online (Sandbox Code Playgroud)

我已经看到了以下问题我如何编写现有的Linq表达式,它向我展示了如何Func<T, bool>使用And表达式组合两个,但我需要能够以更好,更好的方式组合函数.

例如,我有以下两个表达式:

public Expression<Func<T>> ValueExpression { get; private set; }
public Expression<Func<T, bool>> ValidationExpression { get; private set; }
Run Code Online (Sandbox Code Playgroud)

我想创建一个像这样的新表达式:

    public Expression<Func<bool>> IsValidExpression
    {
        get
        {
            // TODO: Compose expressions rather than compile & invoke.
        }
    }
Run Code Online (Sandbox Code Playgroud)

更简洁地我正在尝试创建这些功能:

// Specific case
Func<Expression<Func<T>>, Expression<Func<T, bool>>, Expression<Func<bool>>>
// General case
Func<Expression<Func<X, Y>>, Expression<Func<Y, Z>>, Expression<Func<X, Z>>>
Run Code Online (Sandbox Code Playgroud)

可以修改一般案例函数以根据需要接受不同数量的泛型参数来组成任何函数.

我搜索过Stack Overflow(当然)和网络,但没有一个例子可以解决这个问题.

我的Validator<T>课程代码如下.

public class Validator<T>
{
    public Validator(Expression<Func<T>> valueFunc,
        Expression<Func<T, bool>> validationFunc)
    {
        this.ValueExpression = valueFunc;
        this.ValidationExpression = validationFunc;
    }

    public Expression<Func<T>> ValueExpression { get; private set; }
    public Expression<Func<T, bool>> ValidationExpression { get; private set; }

    public T Value { get { return this.ValueExpression.Compile().Invoke(); } }

    public bool IsValid { get { return this.IsValidExpression.Compile().Invoke(); } }

    public Expression<Func<bool>> IsValidExpression
    {
        get
        {
            // TODO: Compose expressions.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的SelectMany扩展包含了.Compile().Invoke()我想要摆脱的令人讨厌的东西.

public static Validator<U> SelectMany<T, U>(this Validator<T> @this, Expression<Func<T, Validator<U>>> k)
{
    Expression<Func<T>> fvtv = @this.ValueExpression;
    Expression<Func<Validator<U>>> fvu = () => k.Compile().Invoke(fvtv.Compile().Invoke());
    Expression<Func<U>> fvuv = fvu.Compile().Invoke().ValueExpression;
    Expression<Func<U, bool>> fvtiv = u => @this.ValidationExpression.Compile().Invoke(fvtv.Compile().Invoke());
    return fvuv.ToValidator(fvtiv);
}

public static Validator<V> SelectMany<T, U, V>(this Validator<T> @this, Expression<Func<T, Validator<U>>> k, Expression<Func<T, U, V>> s)
{
    Expression<Func<Validator<U>>> fvu = () => @this.SelectMany(k);
    Expression<Func<T>> fvtv = @this.ValueExpression;
    Expression<Func<U>> fvuv = fvu.Compile().Invoke().ValueExpression;
    Expression<Func<T, bool>> fvtiv = @this.ValidationExpression;
    Expression<Func<U, bool>> fvuiv = u => fvu.Compile().Invoke().ValidationExpression.Compile().Invoke(u);
    Expression<Func<V>> fvv = () => s.Compile().Invoke(fvtv.Compile().Invoke(), fvuv.Compile().Invoke());
    Expression<Func<V, bool>> fvviv = v => fvtiv.Compile().Invoke(fvtv.Compile().Invoke()) && fvuiv.Compile().Invoke(fvuv.Compile().Invoke());
    return fvv.ToValidator(fvviv);
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

dtb*_*dtb 19

相当于Haskell的函数组合运算符

(.) :: (b->c) -> (a->b) -> (a->c)
f . g = \ x -> f (g x)
Run Code Online (Sandbox Code Playgroud)

在C#中可能是这样的

static Expression<Func<A, C>> Compose<A, B, C>(
    Expression<Func<B, C>> f,
    Expression<Func<A, B>> g)
{
    var x = Expression.Parameter(typeof(A));
    return Expression.Lambda<Func<A, C>>(
        Expression.Invoke(f, Expression.Invoke(g, x)), x);
}
Run Code Online (Sandbox Code Playgroud)

这是你在找什么?

例:

Compose<int, int, string>(y => y.ToString(), x => x + 1).Compile()(10); // "11"
Run Code Online (Sandbox Code Playgroud)

  • 我们的内部库中有一整套这样的运算符.很遗憾微软不包含使Expression <Func <.. >>真的很棒的东西(相对来说) (4认同)

fel*_*ipe 18

虽然dtb的答案适用于多种场景,但它不是最理想的,因为这样的表达式不能在Entity Framework中使用,因为它无法处理Invoke调用.不幸的是,为了避免这些调用,需要更多的代码,包括一个新的ExpressionVisitor派生类:

static Expression<Func<A, C>> Compose<A, B, C>(Expression<Func<B, C>> f,
                                               Expression<Func<A, B>> g)
{
    var ex = ReplaceExpressions(f.Body, f.Parameters[0], g.Body);

    return Expression.Lambda<Func<A, C>>(ex, g.Parameters[0]);
}

static TExpr ReplaceExpressions<TExpr>(TExpr expression,
                                       Expression orig,
                                       Expression replacement)
    where TExpr : Expression 
{
    var replacer = new ExpressionReplacer(orig, replacement);

    return replacer.VisitAndConvert(expression, nameof(ReplaceExpressions));
}

private class ExpressionReplacer : ExpressionVisitor
{
    private readonly Expression From;
    private readonly Expression To;

    public ExpressionReplacer(Expression from, Expression to)
    {
        From = from;
        To = to;
    }

    public override Expression Visit(Expression node)
    {
        return node == From ? To : base.Visit(node);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将使用第二个表达式中的表达式替换第一个表达式中第一个参数的每个实例.所以像这样的电话:

Compose((Class1 c) => c.StringProperty, (Class2 c2) => c2.Class1Property

会产生表达(Class2 c2) => c2.Class1Property.StringProperty.