Code Sherpa Code Sherpa - 1 year ago 84
C# Question

Linq Expression Trees and Filtering Logic

I am new to Linq Expressions.

I am calling an API, that exposes the following overloaded methods:

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)

My intent is to pass an "id" parameter as part of a predicate in order to filter by the passed value.

Something along the lines of:

x => x.UserId.Equals(id)

My question - is it possible to determine, from the API's method signature, how to achieve this filtering?

I have played around with passing in variations on the following to no avail:

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

I obviously don't understand Expression Trees very well and could use some friendly guidance. Thanks in advance for any insights.

Answer Source

The parameter perdicate of type Expression<Func<TEntity, bool>> is the parameter responsible for filtering:

Expression<Func<Group, bool>> myFunc = u => u.UserId == id;

You need to match the signature of <Group, bool> and not <Group, int>

The final call can be:

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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download