Linq 表达式树和过滤逻辑
Linq Expression Trees and Filtering Logic
我是 Linq 表达式的新手。
我正在调用一个 API,它公开了以下重载方法:
CustomPaging<TEntity> GetAll(int index, int maxPage, Expression<Func<TEntity, int>> keySelector, OrderBy orderBy = OrderBy.Ascending);
CustomPaging<TEntity> GetAll(int index, int maxPage, Expression<Func<TEntity, int>> keySelector, Expression<Func<TEntity, bool>> predicate, OrderBy orderBy, params Expression<Func<TEntity, object>>[] useProperties)
我的意图是传递一个 "id" 参数作为谓词的一部分,以便按传递的值进行过滤。
大致如下:
x => x.UserId.Equals(id)
我的问题 - 是否可以从 API 的方法签名中确定如何实现此过滤?
我试过传递以下变体但无济于事:
Expression<Func<Group, int>> myFunc = u => u.UserId == id
Error: Cannot convert bool to int.
Func<Group, int> myFunc = g => g.UserId == id;
Error: Cannot convert from System.Func to
System.Linq.Expressions.Expression
我显然不太了解表达式树,需要一些友好的指导。提前感谢您的任何见解。
类型Expression<Func<TEntity, bool>>
的参数perdicate
是负责过滤的参数:
Expression<Func<Group, bool>> myFunc = u => u.UserId == id;
您需要匹配 <Group, bool>
而不是 <Group, int>
的签名
最后调用可以是:
var results = GetAll(someIndex, someMaxPage, x=> x.UserId, u => u.UserId == id);
或:
Expression<Func<Group, int>> myKeySelector = u => u.UserId;
Expression<Func<Group, bool>> myFilter = u => u.UserId == id;
var results = GetAll(someIndex, someMaxPage, myKeySelector, myFunc );
我是 Linq 表达式的新手。
我正在调用一个 API,它公开了以下重载方法:
CustomPaging<TEntity> GetAll(int index, int maxPage, Expression<Func<TEntity, int>> keySelector, OrderBy orderBy = OrderBy.Ascending);
CustomPaging<TEntity> GetAll(int index, int maxPage, Expression<Func<TEntity, int>> keySelector, Expression<Func<TEntity, bool>> predicate, OrderBy orderBy, params Expression<Func<TEntity, object>>[] useProperties)
我的意图是传递一个 "id" 参数作为谓词的一部分,以便按传递的值进行过滤。
大致如下:
x => x.UserId.Equals(id)
我的问题 - 是否可以从 API 的方法签名中确定如何实现此过滤?
我试过传递以下变体但无济于事:
Expression<Func<Group, int>> myFunc = u => u.UserId == id
Error: Cannot convert bool to int.
Func<Group, int> myFunc = g => g.UserId == id;
Error: Cannot convert from System.Func to System.Linq.Expressions.Expression
我显然不太了解表达式树,需要一些友好的指导。提前感谢您的任何见解。
类型Expression<Func<TEntity, bool>>
的参数perdicate
是负责过滤的参数:
Expression<Func<Group, bool>> myFunc = u => u.UserId == id;
您需要匹配 <Group, bool>
而不是 <Group, int>
最后调用可以是:
var results = GetAll(someIndex, someMaxPage, x=> x.UserId, u => u.UserId == id);
或:
Expression<Func<Group, int>> myKeySelector = u => u.UserId;
Expression<Func<Group, bool>> myFilter = u => u.UserId == id;
var results = GetAll(someIndex, someMaxPage, myKeySelector, myFunc );