如何构建与通用对象进行比较的Linq表达式树?

时间:2008-10-24 01:12:16

标签: c# linq entity-framework generics expression-trees

我有一个IQueryable和一个T类型的对象。

我想做IQueryable()。其中​​(o => 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));
}

Fyi,GetProperty不是一个有效的功能。我需要能够执行此功能的东西。

我是否有一个星期五下午的大脑融化或这是一件复杂的事情吗?


objectOfTypeT我可以执行以下操作...

var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();

哪种方法很完美,现在我只需要第二部分:

返回SomeIQueryable()。其中​​(o =&gt; o.GetProperty(fieldName) == matchValue);

3 个答案:

答案 0 :(得分:4)

像这样:

    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);

我已经开设了一个博客,其中将涵盖许多表达主题here

如果您遇到任何问题,另一个选择是首先从objectOfTypeT中提取值(使用反射),然后在Expression.Constant中使用该值,但我怀疑它会没问题。是”

答案 1 :(得分:0)

从目前为止我所能看到的,它必须是......

IQueryable<T>().Where(t => 
MemberExpression.Property(MemberExpression.Constant(t), fieldName) == 
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));

虽然我可以通过编译来完成它,但并不是按照需要的方式执行。

答案 2 :(得分:0)

怎么样:

    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值将被加框/取消装箱。