如何编写过滤属性方法的LINQ表达式树?

时间:2013-02-16 15:05:33

标签: c# linq

所以我有一组具有属性的对象:

ParentObject parentObj
{
    string SomeProperty1
    string SomeProperty2
}

在查询这些属性之前,需要将它们设置为ToLower()和Trim()。我明白我能做到:

Expression.Call(pe, typeof(string).GetMethod("Trim", Type.EmptyTypes)); // Or ToLower

Expression.Property(pe, typeof(string).GetProperty("SomeProperty1"));

但我该如何组合它们?

我需要等同于

的东西
from query in parentObjCollection
where query.SomeProperty1.Trim() == "asdf"
select query

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

Expression.Property返回一个表达式本身,您可以将其用作调用的第一个参数(完整示例):

var parent = new ParentObject{ SomeProperty1 = "    test" };
var pe = Expression.Constant(parent);
var property = Expression.Property(pe, typeof(ParentObject).GetProperty("SomeProperty1"));
var call = Expression.Call(property, typeof(string).GetMethod("Trim", Type.EmptyTypes));

var result = Expression.Lambda(call).Compile().DynamicInvoke();

Console.WriteLine(result); // -> "test"

请注意,我必须修改您的Expression.Property来电。