Lucas Freitas Lucas Freitas - 1 month ago 13
C# Question

Dynamic Create Func<T,TR> C#

I'm trying to create a dynamic lambda exp to filter some results on my list, but I can't figure out on how to create a dynamic func<,>

//Here I get the type of my object "Produto", but I can have other objects here...Like "Pedido" or another one.
Type type = typeof(Produto);

var param = Expression.Parameter(type, "arg");
var propName = Expression.Property(param, "Codigo");
var constP = Expression.Constant("123");

var nameStartsWith = Expression.Call(
propName,
typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
constP);

//Here I have to instantiate my Func<T, bool>
//I can't instantiate it with my variable "type" to use on my Where clausule.
//I don't know how to do this in another way, to create my lambda.

var WhereExp = Expression.Lambda<Func<type, bool>>(nameStartsWith, param);

return _uow.produto.GetAll().AsQueryable().Where(WhereExp).ToList();

Answer

You need to create a generic method. Something like this (untested):

public Expression<Func<T, bool>> DynamicWhere<T>(string pname, string value) where T : class
{
    var param = Expression.Parameter(typeof(T), "arg");
    var propName = Expression.Property(param, pname);
    var constP = Expression.Constant(value);

    var nameStartsWith = Expression.Call(
        propName,
        typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
        constP);

    return Expression.Lambda<Func<T, bool>>(nameStartsWith, param);
}

Then you can use it like this:

var WhereExp = DynamicWhere<Produto>("Codigo", "123");

return _uow.produto.GetAll().AsQueryable().Where(WhereExp).ToList();
Comments