如何创建表达式

时间:2010-12-27 11:21:52

标签: c# expression-trees

我有3个变量:

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

如何构建表达式<Func<T, bool>>, 如果T对象具有属性标题

我需要表达式:

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

如果propertyType是bool,那么我需要

item => item.OtherOproperty == false/true

依旧......

1 个答案:

答案 0 :(得分:2)

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

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();