动态创建功能<t,tr> C#

时间:2016-11-03 01:57:53

标签: c# linq entity

我正在尝试创建一个动态lambda exp来过滤我列表中的一些结果,但我无法弄清楚如何创建动态函数&lt;,&gt;

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

1 个答案:

答案 0 :(得分:2)

您需要创建一个通用方法。像这样(未经测试):

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

然后你可以像这样使用它:

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

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