Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a nested generic Expression<Func<T, bool>>

Tags:

c#

.net

lambda

linq

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:

Using reflection to address a Linqed property

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

Runtime creation of generic Func<T>

like image 717
Axl Avatar asked May 13 '09 19:05

Axl


2 Answers

You need to make the method itself generic:

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
                                                  -+-
                                                   ^
                                                   +- this
like image 167
Lasse V. Karlsen Avatar answered Sep 20 '22 12:09

Lasse V. Karlsen


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);
}
like image 25
mmx Avatar answered Sep 22 '22 12:09

mmx