【问题标题】:How to create Expression如何创建表达式
【发布时间】:2010-12-27 11:21:52
【问题描述】:

我有 3 个变量:

String propertyName = "Title";
String propertyValue = "Bob";
Type propertyType = typeof(String);

如何构造表达式<Func<T, bool>>, 如果T 对象有属性Title

我需要表达:

item => item.Title.Contains("Bob")

如果 propertyType 是 bool,那么我需要

item => item.OtherOproperty == false/true

等等……

【问题讨论】:

    标签: c# expression-trees


    【解决方案1】:

    此代码执行过滤并将结果存储在过滤后的数组中:

    IQueryable<T> queryableData = (Items as IList<T>).AsQueryable<T>();
    
    PropertyInfo propInfo = typeof(T).GetProperty("Title");
    ParameterExpression pe = Expression.Parameter(typeof(T), "Title");
    Expression left = Expression.Property(pe, propInfo);
    Expression right = Expression.Constant("Bob", propInfo.PropertyType);
    Expression predicateBody = Expression.Equal(left, right);
    
    // Create an expression tree that represents the expression            
    MethodCallExpression whereCallExpression = Expression.Call(
        typeof(Queryable),
        "Where",
        new Type[] { queryableData.ElementType },
        queryableData.Expression,
        Expression.Lambda<Func<T, bool>>(predicateBody, new ParameterExpression[] { pe }));
    
    T[] filtered = queryableData.Provider.CreateQuery<T>(whereCallExpression).Cast<T>().ToArray();
    

    【讨论】:

    • 感谢您的回答。你能解释一下,如何在这里定义'Contains','StartsWith','EndsWith'等函数吗?
    • 我建议使用 Expression.Equal 方法的另一个重载并指定 MethodInfo 执行所需的相等检查(不是通常的相等,而是您的自定义 - “LIKE”相等)。但我不确定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多