tags:

views:

501

answers:

3

The error message is "The type or namespace name 'T' could not be found."

???

public static Expression<Func<T, bool>> MakeFilter(string prop, object val)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    PropertyInfo pi = typeof(T).GetProperty(prop);
    MemberExpression me = Expression.MakeMemberAccess(pe, pi);
    ConstantExpression ce = Expression.Constant(val);
    BinaryExpression be = Expression.Equal(me, ce);
    return Expression.Lambda<Func<T, bool>>(be, pe);
}

Related links:

http://stackoverflow.com/questions/791187/using-reflection-to-address-a-linqed-property

http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/

http://stackoverflow.com/questions/658316/runtime-creation-of-generic-funct

+2  A: 

There's no generic argument defined for your method. You should define one (MakeFilter<T>):

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    PropertyInfo pi = typeof(T).GetProperty(prop);
    MemberExpression me = Expression.MakeMemberAccess(pe, pi);
    ConstantExpression ce = Expression.Constant(val);
    BinaryExpression be = Expression.Equal(me, ce);
    return Expression.Lambda<Func<T, bool>>(be, pe);
}
Mehrdad Afshari
+2  A: 

The method needs to be declared as generic (MakeFilter<T>):

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)

Otherwise, how else would the caller be able to specify what T is?

Rex M
+4  A: 

You need to make the method itself generic:

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
                                                  -+-
                                                   ^
                                                   +- this
Lasse V. Karlsen
Nice way to denote the difference.
Rex M
Which reminded me to create my MarkDown wish list: http://www.vkarlsen.no/index.php?title=MarkDown_Wishlist
Lasse V. Karlsen