4

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

我想做 IQueryable().Where(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));
}

仅供参考,GetProperty 不是有效函数。我需要执行此功能的东西。

我是周五下午的大脑融化了还是这是一件复杂的事情?


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

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

效果很好,现在我只需要第二部分:

return SomeIQueryable().Where(o => o.GetProperty(fieldName) == matchValue);

4

3 回答 3

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,但我怀疑“原样”会很好。

于 2008-10-24T03:57:18.670 回答
0

从我目前所看到的情况来看,它必须是......

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

虽然我可以编译它,但它并没有完全按照所需的方式执行。

于 2008-10-24T02:29:03.247 回答
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);
    }

这是一种在不使用动态查询的情况下通过字符串获取属性值的方法。缺点是所有值都将被装箱/拆箱。

于 2012-04-04T19:14:43.420 回答