Convert string to Func

c# expression-trees lambda linq


I have the following method

     public List<ServicesLogModel> Paging(Func<ServicesLogModel, bool> condition, string columnOrder, bool? orderDescending, int? pageIndex, int? pageSize, out int total)
         return _mongoRepository.Paging(condition, order => order.Message, orderDescending.Value, pageIndex.Value, pageSize.Value, out total);

The columnOrder parameter is a string as lambda expression (ex: order => order.Message) that I must cast to Func<T, object>

I'm trying with Expression.Parameter

 var parm = Expression.Parameter(typeof(ServicesLogModel), "order");

        var propName = Expression.Property(parm, columnOrder);

        Expression predicateBody = Expression.Assign(parm, propName);

        var test=Expression.Lambda<Func<ServicesLogModel, object>>(predicateBody, parm);

it doesn't work Error :You can not use an expression of type 'System.String' for an assignment to type 'ServicesLogModel'

Edit :Method Signature

public List<T> Paging(Func<T, bool> condition, Func<T, object> order, bool orderDescending, int pageIndex, int pageSize,out int total) 

Call method

    public IActionResult GetReaderConnectorLog(string Apikey, string SecretKey, int? index, int? pagesize, bool? orderAsc, string columnOrder)
            //  _webApiHelper.ValidateApiKey(Apikey, SecretKey, Context, _userService, true);
            int total;
            var listModel = _connectorLogService.Paging(_ => true, $"order => order.{columnOrder}", orderAsc, index, pagesize, out total);
            return _webApiHelper.OkResponse($"{_appSettings.Options.UserTag}[Send List User]", Context, new PaginationModel<ServicesLogModel> { ListData = listModel, Total = total, Apikey = Apikey, SecretKey = SecretKey });
        catch (Exception e)
            return _webApiHelper.ResolveException(Context, e);


9/22/2015 6:05:05 PM

Popular Answer

Well , the final solution was this

public Func<T, object> GetLambda<T>(string property)
        var param = Expression.Parameter(typeof(T), "p");

        Expression parent = Expression.Property(param, property);

        if (!parent.Type.IsValueType)
            return Expression.Lambda<Func<T, object>>(parent, param).Compile();
        var convert = Expression.Convert(parent, typeof(object));
        return Expression.Lambda<Func<T, object>>(convert, param).Compile();
9/23/2015 1:19:13 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow