views:

1087

answers:

2

I have an IQueryable and an object of type T.

I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))

so ...

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 isn't a valid function. I need something which performs this function.

Am I having a Friday afternoon brain melt or is this a complex thing to do?


objectOfTypeT I can do the following ...

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

Which works perfectly,now I just need the second part:

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

A: 

From what I can see so far it's going to have to be something like ...

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

While I can get this to compile it's not quite executing the way it is required.

JTew
Close; you need to build a LambdaExpression - see my post.
Marc Gravell
+3  A: 

Like so:

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

I have started a blog which will cover a number of expression topics, here.

If you get any problems, another option is to extract the value from objectOfTypeT first (using reflection) and then use that value in the Expression.Constant, but I suspect it'll be fine "as is".

Marc Gravell
Perfect. Exactly what I needed.Now to figure out exactly what is going on :)
JTew
@JTew - the blog entry might shine some light...
Marc Gravell