本文介绍了如何创建表情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个变量:
String propertyName = "Title";
String propertyValue = "Bob";
Type propertyType = typeof(String);
如何构造表达式<Func<T, bool>>
,如果T
对象具有属性标题?
How can I construct Expression <Func<T, bool>>
,if T
object has property Title?
我需要表达:
item => item.Title.Contains("Bob")
如果propertyType是bool,那么我需要
if propertyType is bool, then I need
item => item.OtherOproperty == false/true
以此类推...
推荐答案
此代码执行过滤并将结果存储在过滤后的数组中:
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();
这篇关于如何创建表情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!