如何在c#中动态生成Lambda表达式

时间:2016-02-14 23:50:04

标签: c# lambda

我想做以下事情;

    public IEnumerable<SalesRegister> GetSalesRegister()
    {
        return _client.GetAllSalesRegisters().OrderBy(x => x.CompanyName);
    }

做类似的事情;

    public IEnumerable<SalesRegister> GetSalesRegister(string sortBy)
    {
        return _client.GetAllSalesRegisters().OrderBy(x => sortBy);
    }

为此,我尝试了以下内容,但没有工作

    public IEnumerable<SalesRegister> GetSalesRegister(string sortBy)
    {
        var type = typeof(SalesRegister);
        var param = Expression.Parameter(type, "x");
        var len = Expression.PropertyOrField(param, sortBy);
        return _client.GetAllSalesRegisters().OrderBy(x => len );
    }

我不确定我是否可以这样做,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

试试这个 -

public IEnumerable<SalesRegister> GetSalesRegister(Expression<Func<SalesRegister, object>> sortByExp)
{
    return _client.GetAllSalesRegisters().OrderBy(sortByExp.Compile());
}

你可以这样称呼它 -

GetSalesRegister(x => x.CompanyName);

要传递lambda表达式,您需要将类型设置为Expression<Func<T, TR>>,其中T是基类,TR是表达式的返回类型

或者,如果您只有字符串名称,请尝试构建表达式 -

public IEnumerable<SalesRegister> GetSalesRegister(string sortBy)
{
    var param = Expression.Parameter(typeof (SalesRegister), "x");
    var prop = typeof (SalesRegister).GetProperty(sortBy);
    var objectFuncType = typeof (Func<,>).MakeGenericType(typeof (SalesRegister), prop.PropertyType);
    var propExp = Expression.PropertyOrField(param, sortBy);
    var exp = Expression.Lambda(objectFuncType, propExp, param);
    var converted = Expression.Convert(exp.Body, typeof (object)); // only needed if you are passing in no referene types like int, double, etc as parameters, otherwise ignore this line and use 'exp' in place of 'converted' in the next line
    var sortByExp= Expression.Lambda<Func<SalesRegister, object>>(converted, exp.Parameters);

    return _client.GetAllSalesRegisters().OrderBy(sortByExp.Compile());
}

你可以这样称呼它 -

GetSalesRegister("CompanyName");