我怎么建立一个皇宫的表达的树比较,对一个通用的对象?
-
04-07-2019 - |
题
我有一个IQueryable和类型的对象T.
我想要做的IQueryable().在哪里(o=>。GetProperty(fieldName)==objectOfTypeT.GetProperty(fieldName))
所以...
public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
仅供参考,GetProperty不是一个有效功能。我需要一些东西,执行这一功能。
我有一个星期五下午的大脑融化或者这是一个复杂的事情吗?
objectOfTypeT我可以做以下...
var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
这完美的作品,现在我只需要第二部分:
回SomeIQueryable().在哪里(o=> o.GetProperty(fieldName) ==matchValue);
解决方案
像这样:
var param = Expression.Parameter(typeof(T), "o");
var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
var body = Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.PropertyOrField(fixedItem, fieldName));
var lambda = Expression.Lambda<Func<T,bool>>(body,param);
return source.Where(lambda);
我已经开始了一个博客,其中将涵盖数量表达的主题, 在这里,.
如果你得到的任何问题,另一个选择是中提取价值从 objectOfTypeT
第(使用反射)和随后的使用得值 Expression.Constant
, 但我怀疑它会被罚款。
其他提示
从什么我可以看到到目前为止,它必须喜欢的东西...
IQueryable<T>().Where(t =>
MemberExpression.Property(MemberExpression.Constant(t), fieldName) ==
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));
虽然我可以得到这个编译它并不完全执行的方式,它是必需的。
什么约:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public Func<T, TRes> GetPropertyFunc<T, TRes>(string propertyName)
{
// get the propertyinfo of that property.
PropertyInfo propInfo = typeof(T).GetProperty(propertyName);
// reference the propertyinfo to get the value directly.
return (obj) => { return (TRes)propInfo.GetValue(obj, null); };
}
public void Run()
{
List<Person> personList = new List<Person>();
// fill with some data
personList.Add(new Person { Name = "John", Age = 45 });
personList.Add(new Person { Name = "Michael", Age = 31 });
personList.Add(new Person { Name = "Rose", Age = 63 });
// create a lookup functions (should be executed ones)
Func<Person, string> GetNameValue = GetPropertyFunc<Person, string>("Name");
Func<Person, int> GetAgeValue = GetPropertyFunc<Person, int>("Age");
// filter the list on name
IEnumerable<Person> filteredOnName = personList.Where(item => GetNameValue(item) == "Michael");
// filter the list on age > 35
IEnumerable<Person> filteredOnAge = personList.Where(item => GetAgeValue(item) > 35);
}
这是一个办法得到价值观的一个属性串无需使用的动态查询。缺点是al值将盒装/拆箱.
不隶属于 StackOverflow