簡體   English   中英

在c#中創建表達式樹

[英]Create an expression tree in c#

我試圖在LINQ中使用表達式樹創建一個動態查詢來表示以下查詢

WageConstIns.Where(WageConstIn => WageConstIn.Serialno.ToString().StartsWith("2800"));

我試圖像這樣創建它:

MemberExpression le1 = LinqExpression.Property(paramExp, "Serialno");
MethodCallExpression le2 = LinqExpression.Call(le1, typeof(string).GetMethod("ToString",  System.Type.EmptyTypes));
ConstantExpression le3 = LinqExpression.Constant("2800");
MethodCallExpression le4 = LinqExpression.Call(le2, typeof(string).GetMethod("StartsWith"));

我在運行時遇到錯誤。 如何使用表達式樹最好地構建上述查詢?

最簡單的方法是將其聲明為Expression<Func<...>>

public static class Program {
    public static void Main() {
        Expression<Func<DummyClass, Boolean>> predicate = WageConstIn => WageConstIn.Serialno.ToString().StartsWith("2800");
    }
}

但是如果你想用不同的表達式構建它...

public static class Program {
    public static void Main() {
        var param = Expression.Parameter(typeof(DummyClass), "WageConstIn");
        var constValue = Expression.Constant("2800");

        // WageConstIn => WageConstIn.Serialno.ToString().StartsWith(...)
        var first = Expression.Lambda(
            parameters: param,
            body: Expression.Call(
                instance: Expression.Call(
                    instance: Expression.Property(param, "Serialno"),
                    methodName: "ToString",
                    typeArguments: null,
                    arguments: null
                ),
                methodName: "StartsWith",
                typeArguments: null,
                arguments: new[] { constValue }
            )
        );

        // WageConstIn => Convert.ToString(WageConstIn.Serialno).StartsWith(...)
        var second = Expression.Lambda(
            parameters: param,
            body: Expression.Call(
                instance: Expression.Call(
                    type: typeof(Convert),
                    methodName: "ToString",
                    typeArguments: null,
                    arguments: new[] { Expression.Property(param, "Serialno") }
                ),
                methodName: "StartsWith",
                typeArguments: null,
                arguments: new[] { constValue }
            )
        );
    }
}

進入表達式樹域的大多數[我已經與之交談]的人通常對System.Linq.Dynamic功能感到滿意。 (這可以被濫用到很多不同的方式。)這個純粹的awesomeness代碼片段是Visual Studio示例代碼的一部分,可能已經隱藏在你的硬盤驅動器的某個地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM