【发布时间】:2015-09-22 17:03:15
【问题描述】:
我有以下方法
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);
}
columnOrder 参数是一个字符串作为 lambda 表达式(例如:order => order.Message),我必须将其转换为 Func<T, object>
我正在尝试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);
它不起作用 错误:您不能使用“System.String”类型的表达式来分配“ServicesLogModel”类型
编辑:方法签名
public List<T> Paging(Func<T, bool> condition, Func<T, object> order, bool orderDescending, int pageIndex, int pageSize,out int total)
调用方法
[HttpGet]
[Route("Admin/GetReaderConnectorLog/{Apikey}/{SecretKey}/{index}/{pagesize}/{orderAsc}/{columnOrder}")]
public IActionResult GetReaderConnectorLog(string Apikey, string SecretKey, int? index, int? pagesize, bool? orderAsc, string columnOrder)
{
try
{
_userService.BeginTransaction();
// _webApiHelper.ValidateApiKey(Apikey, SecretKey, Context, _userService, true);
int total;
//TEST
var listModel = _connectorLogService.Paging(_ => true, $"order => order.{columnOrder}", orderAsc, index, pagesize, out total);
_userService.Commit();
return _webApiHelper.OkResponse($"{_appSettings.Options.UserTag}[Send List User]", Context, new PaginationModel<ServicesLogModel> { ListData = listModel, Total = total, Apikey = Apikey, SecretKey = SecretKey });
}
catch (Exception e)
{
_userService.Rollback();
return _webApiHelper.ResolveException(Context, e);
}
}
问候
【问题讨论】:
-
定义“它不起作用”
-
仅作记录,当您的返回类型为布尔值时,您可以使用 Predicate
而不是 Func 。 -
@msmolcic
Predicate早于Func,使用更通用的Func是完全可以接受的。参见例如 LINQ 的 Where clausepublic static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )。所有 LINQ 都使用Func<T, bool>,并且没有任何地方使用Predicate<T>。 -
@ScottChamberlain 实际上他可以更改分页并使用谓词
标签: c# linq lambda expression-trees