2

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();
Lucas Freitas
  • 1,016
  • 4
  • 16
  • 37
  • Can you create **interface** for this unknown type? – Lei Yang Nov 03 '16 at 02:01
  • What do you mean by "dynamic" Func exactly? – Abion47 Nov 03 '16 at 02:02
  • If you can create a function on `_uow` with a generic type it'd work better, I think. – Vagner Lucas Nov 03 '16 at 02:09
  • What is preventing you from passing the type in as a generic type at compile time? Do you not know the type at compile time? – David L Nov 03 '16 at 02:12
  • @Abion47 I want to instantiate my Expression.Lambda> with a generic type, for example In this case, my "type" var is a typeof(Produto), but it can be a typeof(someOtherObject) – Lucas Freitas Nov 03 '16 at 02:13
  • 1
    Possible duplicate of [How to create a Expression.Lambda when a type is not known until runtime?](http://stackoverflow.com/questions/7801165/how-to-create-a-expression-lambda-when-a-type-is-not-known-until-runtime) – David L Nov 03 '16 at 02:14
  • @DavidL I dunno, My method gonna receive a random type and I have to set it do my func<> – Lucas Freitas Nov 03 '16 at 02:22
  • I'm suspecting that this might be an XY problem. What is your actual goal here? – Abion47 Nov 03 '16 at 02:53

1 Answers1

2

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();
Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29