How to create Expression

ぃ、小莉子 提交于 2020-01-06 06:08:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!