问题
I have 3 variables:
String propertyName = "Title";
String propertyValue = "Bob";
Type propertyType = typeof(String);
How can I construct Expression <Func<T, bool>>
,
if T
object has property Title?
I need Expression:
item => item.Title.Contains("Bob")
if propertyType is bool, then I need
item => item.OtherOproperty == false/true
and so on...
回答1:
This code performs filtering and stores results in filtered array:
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();
来源:https://stackoverflow.com/questions/4538334/how-to-create-expression