在C#中创建表达式树

5

我试图使用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"));

我在运行时遇到了错误。如何使用表达式树来构建上述查询最好?


你为什么不告诉我们你遇到了什么错误? - LukeH
1个回答

7
最简单的方法就是将其声明为 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功能感到满意。(它可以被滥用成很多不同的方式。)这个代码片段极其强大,并且是Visual Studio示例代码的一部分,可能已经隐藏在您的硬盘上了。


请帮忙处理表达式树:DummyCol.Where(DummyItem => Convert.ToString(DummyItem.Serialno).StartsWith("2008"))。 - Waliaula Makokha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接